IF Statement Multiple Answers - Same Result Javascript

扶醉桌前 提交于 2019-12-13 04:23:15

问题


Is their a method to have multiple right answers with the same result?

 function check(code){
    if(code == (8 || 9 || 13 || 16 || 17 || 18 || 20 || 32)){
      return true;
    }
 }

I know I can use a switch statement, but I was wondering if their is anyway similar to this. I already tried using an array but its slow.

I also realise that you can use && but I don't want to have to type code == a hundred times.


回答1:


consider using an array

function check(code){
    return [8,9,13,16,17,18,20,32].indexOf(code) != -1;
}

Note that the indexOf method is a part of ECMA5 and may not be available in some browsers.

See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf for full document.




回答2:


You either have to do this

return code == 8 || code == 9 || ...;

or this

return [8, 9, 13, ...].indexOf(code) > 0;



回答3:


Nope, you've got to spell them all out.

A better way would be a loop:

var values = [8, 9, 13, 16, 17, 18, 20, 32];
for (i = 0; i < values.length; ++i) {
    if (code === values[i]) {
        // do something.
    }
}



回答4:


How about that:

function check(code){
   return [8, 9, 13, 16, 17, 18, 20, 32].indexOf(code) != -1;
}


来源:https://stackoverflow.com/questions/8711174/if-statement-multiple-answers-same-result-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!