javascript if语句未按预期评估

时间:2017-11-10 21:22:34

标签: javascript if-statement conditional-statements

为什么我的“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"

1 个答案:

答案 0 :(得分:2)

您的问题是您使用了错误的AND操作符,您需要使用&&代替&

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

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

请详细了解 What's the difference between & and && in JavaScript?