Javascript 将数组转换为switch语句
将数组转换为switch语句的最快解决方案是什么Javascript 将数组转换为switch语句,javascript,arrays,switch-statement,Javascript,Arrays,Switch Statement,将数组转换为switch语句的最快解决方案是什么 var myArr = [x,y] case x: console.log("ok > x") break; case y: console.log("ok > y") break; 像这样 arr.map(function(I) { console.log('ok >' + I); }); 如果我对你的问题猜对了。像这样 arr.map(function(I) { console.
var myArr = [x,y]
case x:
console.log("ok > x")
break;
case y:
console.log("ok > y")
break;
像这样
arr.map(function(I) { console.log('ok >' + I); });
如果我对你的问题猜对了。像这样
arr.map(function(I) { console.log('ok >' + I); });
如果我对你的问题猜对了
将数组转换为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');
}
}
*/
功能ARRTOS开关(a,x){
var代码=[];
push(“var f=函数(x){”);
代码.按下(“开关(x){”);
对于(var i=0,j=a.length;i
将数组转换为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');
}
}
*/
功能ARRTOS开关(a,x){
var代码=[];
push(“var f=函数(x){”);
代码.按下(“开关(x){”);
对于(var i=0,j=a.length;我能解释一下你想要实现什么吗?数组是数据结构,交换机是流量控制指令-完全不同的东西。你能解释一下你想要实现什么吗?数组是数据结构,交换机是流量控制指令-完全不同的东西。记住,你需要添加Array.map()
对于较旧的浏览器手动添加:不较旧,但仅限trident…grrrr..无论如何,谢谢你的这封便条+@Joe!记住,对于较旧的浏览器,你需要手动添加Array.map()
对于较旧的浏览器:不较旧,但仅限trident…grrrr..无论如何,谢谢你的这封便条+@Joe!