这是我的代码
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语句?
答案 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/
上发布此类问题答案 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>";
}