将数组转换为 switch 语句
将数组转换为 switch 语句最快的解决方案是什么?
var myArr = [x,y]
case x:
console.log("ok > x")
break;
case y:
console.log("ok > y")
break;
What's the fastest solution to convert a array into a switch statement?
var myArr = [x,y]
case x:
console.log("ok > x")
break;
case y:
console.log("ok > y")
break;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
小女人ら2024-12-01 21:17:00
将数组转换为 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');
}
}
*/
请注意,上述内容毫无意义,超出了丑陋和危险的范围。使用后果自负。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
像这样
如果我对你的问题的猜测正确的话。
like this
If I'm guessing correctly concerning your question.