【问题标题】:simplify IF statement with multiple OR || conditions for the same variable用多个 OR 简化 IF 语句 ||相同变量的条件
【发布时间】:2014-11-10 16:25:41
【问题描述】:

这是我的代码

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

【问题讨论】:

标签: javascript if-statement multiple-conditions


【解决方案1】:

试试这个:

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,2,3,5,6,7].includes(something) 不是更好吗?
【解决方案2】:

您可以随时反转您的支票:

var something = 4;

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

【讨论】:

    【解决方案3】:
    let something = "four";
    
    if ( ["one","two","three","five","six","seven"].includes(something) ) {
        document.body.innerHTML = "<h1>yes</h1>";
    } else {
        document.body.innerHTML = "<h1>no</h1>";
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      相关资源
      最近更新 更多