什么是将数组转换为switch语句的最快解决方案?将数组转换为switch语句
var myArr = [x,y]
case x:
console.log("ok > x")
break;
case y:
console.log("ok > y")
break;
什么是将数组转换为switch语句的最快解决方案?将数组转换为switch语句
var myArr = [x,y]
case x:
console.log("ok > x")
break;
case y:
console.log("ok > y")
break;
什么是将数组转换为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');
}
}
*/
注意,上面是相当没有意义,超出了丑陋的和危险的那个。用于自己的危险。
哈哈确定了它:) – mate64
你能解释一下你想达到什么吗?数组是数据结构,开关是流控制指令 - 完全不同的东西。 – Mat