开发者

Converting an array to a switch statement

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;


like this

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

If I'm guessing correctly concerning your question.


What's the fastest solution to convert a array into a switch statement?

...just for fun, I'm taking your request literally:

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');
 }
}
*/

Note that the above is rather pointless, beyond ugly and dangerous at that. Use at your own peril.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜