【问题标题】:javascript : Detecting result of a logical OR conditionjavascript:检测逻辑或条件的结果
【发布时间】:2016-01-02 05:33:07
【问题描述】:

是否有内置方法来检测逻辑或条件中的哪一半为真?

// foo would return true or false    
if (thing1 === "3" || thing2 === foo()) {
     // do something if thing1 is 3
     // do something different if thing2 is true    
};

或者我应该只使用两个嵌套的 if 块吗?

【问题讨论】:

    标签: javascript loops if-statement conditional logical-operators


    【解决方案1】:

    使用两个 if 块。没有内置的方法可以做到这一点。

    此外,如果foo() 返回真或假,则不需要thing2 === foo(),并且末尾的分号是无关的。

    if (thing1 === "3") {
         // do something 
    } else if (foo()) {
         // do something else
    }
    

    【讨论】:

    • 正是我想要的。谢谢!
    • foo()是真还是假不等于问thing2 === foo()
    【解决方案2】:

    我不确定“嵌套”部分,但通常它只是简单地完成:

    if (thing1 === "3") {
         // do something if thing1 is 3
    } else if (thing2 === foo()) {
        // do something different if thing2 is true
    }
    

    【讨论】:

      【解决方案3】:

      是的。不要把它放在一起:

      if (thing1 === "3") {
      
           // do something if thing1 is 3
      }
      else if(thing2 === foo()) {
      
           // do something different if thing2 is 'equal to return value of foo()'
      }
      

      无论如何嵌套都不起作用,因为它是一个条件。

      【讨论】:

        【解决方案4】:

        使用ifelseif 是一个不错的选择

        if ("3" === thing1) {
         // do something if thing1 is 3 
        } else if (thing2  === foo()) {
         // do something different if thing2 is true
        }
        

        【讨论】:

          猜你喜欢
          • 2014-10-29
          • 2017-01-08
          • 1970-01-01
          • 2015-02-27
          • 1970-01-01
          • 1970-01-01
          • 2017-11-23
          • 1970-01-01
          • 2010-10-02
          相关资源
          最近更新 更多