使用多个OR ||简化IF语句同一变量的条件

时间:2014-09-16 19:29:32

标签: javascript if-statement multiple-conditions

这是我的代码

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>";
}

如果所有条件都考虑相同的变量,有没有办法简化IF语句?

DEMO

2 个答案:

答案 0 :(得分:3)

试试这个:

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/

另外,请在https://codereview.stackexchange.com/

上发布此类问题

答案 1 :(得分:0)

您可以随时反转支票:

var something = 4;

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