simplify IF statement with multiple OR || conditions for the same variable

半腔热情 提交于 2020-01-04 13:46:15

问题


Here's my code

var something = "four";

if(
    something == "one" || 
    something == "two" || 
    something == "three" ||
    something == "five" ||
    something == "six" ||
    something == "seven"
){
    document.body.innerHTML = "<h1>yes</h1>";
}else{
    document.body.innerHTML = "<h1>no</h1>";
}

Is there a way to simplify the IF statement given that all the conditions regard the same variable?

DEMO


回答1:


Try this:

var something = 4;

if([1,2,3,5,6,7].indexOf(something) > -1) {
 document.body.innerHTML = "<h1>yes</h1>";
} else {
 document.body.innerHTML = "<h1>no</h1>";
}

JSFiddle: http://jsfiddle.net/2onn6Lc2/1/

Also, please post this type of question on https://codereview.stackexchange.com/




回答2:


You could always invert your check:

var something = 4;

if(
    something < 1 || 
    something == 4 || 
    something >7
){
    document.body.innerHTML = "<h1>no</h1>";
}else{
    document.body.innerHTML = "<h1>yes</h1>";
}


来源:https://stackoverflow.com/questions/25876928/simplify-if-statement-with-multiple-or-conditions-for-the-same-variable

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