2011-07-15 81 views
0

什么是将数组转换为switch语句的最快解决方案将数组转换为switch语句

var myArr = [x,y] 

    case x: 
    console.log("ok > x") 
    break; 
    case y: 
    console.log("ok > y") 
    break; 
+5

你能解释一下你想达到什么吗?数组是数据结构,开关是流控制指令 - 完全不同的东西。 – Mat

回答

3

这样

arr.map(function(I) { console.log('ok >' + I); }); 

如果我猜正确关于你的问题。

+0

请记住,您需要为旧版浏览器手动添加'Array.map()':https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/map#Compatibility – gilly3

+0

不是旧的,而是三叉戟只有... grrrr ..无论如何,谢谢你的这个笔记+ @Joe! – mate64

2

什么是将数组转换为switch语句的最快解决方案?

...只是为了好玩,我要带你的要求的字面:

function arrToSwitch(a, x) { 
    var code = []; 
    code.push("var f = function (x) {"); 
    code.push(" switch (x) {"); 
    for (var i=0, j=a.length; i<j; i++) { 
    code.push(" case " + a[i] + ": console.log('ok > " + a[i] + "'); break;"); 
    } 
    code.push(" default: console.log('not found');"); 
    code.push(" }\n}"); 
    eval(code.join("\n")); 
    return f; 
} 

var myArr = [1, 2, 3]; 
var test = arrToSwitch(myArr); 
test(3) // logs "ok > 3" to the console 
test(4) // logs "not found" to the console 

console.log(test); 
/* returns 
function (x) { 
switch (x) { 
    case 1: console.log('ok > 1'); break; 
    case 2: console.log('ok > 2'); break; 
    case 3: console.log('ok > 3'); break; 
    default: console.log('not found'); 
} 
} 
*/ 

注意,上面是相当没有意义,超出了丑陋的和危险的那个。用于自己的危险。

+0

哈哈确定了它:) – mate64