今天在我的应用程序中涉及JavaScript代码时,我注意到了一些奇怪的东西。
var someVar = 25;
var anotherVar = 50;
var out = (anotherVar == 50 && someVar);
console.log(out) // outputs 25 and not true or false;
你有任何想法发生了什么吗?
今天在我的应用程序中涉及JavaScript代码时,我注意到了一些奇怪的东西。
var someVar = 25;
var anotherVar = 50;
var out = (anotherVar == 50 && someVar);
console.log(out) // outputs 25 and not true or false;
你有任何想法发生了什么吗?
&&
运算符:&&
如果两个操作数都为true,则返回true;否则返回false。anotherVar == 50
)是true(不是false),因此它返回expr2 (someVar
),即25
。true
或false
,因为expr2不是布尔值。
ECMA-262规范指出:
&&
或||
运算符产生的值不一定是布尔类型。产生的值始终是两个操作数表达式之一的值。
arg1 = arg1 || "default";
(只要假值(比如 null 等)不是有效值)。 - Izkata
(anotherVar == 50 && someVar == 25)
是什么意思? - Bharadwaj