问题
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