This question already has answers here:
What's the difference between & and && in JavaScript?
                                
                                    (4个答案)
                                
                        
                                2年前关闭。
            
                    
为什么我的“ C”条件转到“ else”语句?他们分开了要进入“ if”语句,但在一起却不起作用。

var objTest = {
    ID : "10"
};

//A: First Condition: Exist value in property ID
console.log((objTest.ID ? 'if' : 'else'));                      // output => "if"

//B: Second Condition: Value different from "0"
console.log((objTest.ID != "0" ? 'if' : 'else'));               // output => "if"

//C: First and Second Condition together must be "if"
console.log((objTest.ID & objTest.ID != "0" ? 'if' : 'else'));  // output => "else"

最佳答案

您的问题是您使用了错误的AND运算符,需要使用&&而不是&

console.log((objTest.ID && objTest.ID != "0" ? 'if' : 'else'));


第一个&是按位运算符,而&&是逻辑运算符。

请查看What's the difference between & and && in JavaScript?了解更多详细信息。

关于javascript - javascript if语句未按预期评估,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47231313/

10-12 00:06
查看更多