用多个OR ||简化IF语句相同变量的条件 [英] simplify IF statement with multiple OR || conditions for the same variable
本文介绍了用多个OR ||简化IF语句相同变量的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码
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语句?
Is there a way to simplify the IF statement given that all the conditions regard the same variable?
推荐答案
尝试一下:
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/
JSFiddle: http://jsfiddle.net/2onn6Lc2/1/
另外,请在 https://codereview.stackexchange.com/
这篇关于用多个OR ||简化IF语句相同变量的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文