简体   繁体   English

为什么`int(0)和boolean`返回`int(0)`而不是`boolean(false)`?

[英]Why `int(0) and boolean` returns `int(0)` instead `boolean(false)`?

Specifically (I don't know if it can happen in others case), when I do int(0) && boolean with myString.length && myString === "true" when myString = "" , it returns 0 instead of returns a boolean. 具体来说(我不知道是否会在其他情况下发生),当我在myString = ""时使用myString.length && myString === "true"执行int(0) && boolean时,它返回0而不是返回a布尔值。

alert((function() {
    var myString = "";
    return myString.length && myString === "true";
})());

I know that I can fix it by do myString.length !== 0 or casting with Boolean . 我知道我可以通过执行myString.length !== 0或使用Boolean进行修复。 But I like to understand why && don't force cast the left side to boolean. 但我喜欢理解为什么&&不强制将左侧强制转换为布尔值。

Live example : http://jsfiddle.net/uqma4ahm/1/ 实例http//jsfiddle.net/uqma4ahm/1/

The && operator in JavaScript returns the actual value of whichever one of its subexpression operands is last evaluated. JavaScript中的&&运算符返回上次评估其子表达式操作数中的任何一个的实际值。 In your case, when .length is 0 , that expression is the last to be evaluated because 0 is "falsy". 在你的情况下,当.length0 ,该表达式是最后要评估的,因为0是“falsy”。

The operator does perform a coercion to boolean of the subexpression value(s), but it only uses that result to determine how to proceed. 运算符确实对子表达式值的布尔值执行强制,但它仅使用该结果来确定如何继续。 The overall value of the && is thus not necessarily boolean; 因此, &&的整体价值不一定是布尔值; it will be boolean only when the last subexpression evaluated had a boolean result. 只有在评估的最后一个子表达式具有布尔结果时,它才是布尔值。

This JavaScript behavior is distinctly different from the behavior of the similar operator in C, C++, Java, etc. 这种JavaScript行为明显不同于C,C ++,Java等中类似运算符的行为。

The && operator yields the left hand value if it is false-y 1 and the right-hand value otherwise. 如果它是false-y 1&&运算符产生左手值,否则产生右手值。 (Unlike some languages, it is not guaranteed to evaluate to true or false!) (与某些语言不同, 不能保证评估结果为true或false!)

TTL for A && B: A && B的TTL:

A         B     (A && B)
false-y   -     A
truth-y   -     B

To make sure that only true or false is returned, it is easy to apply (double) negation: 为了确保返回true或false,很容易应用(double)否定:

return !!(myString.length && myString === "true")

or, equivalently 或者,等效地

return !(!myString.length || myString !== "true")

Here is the negation TTL which leads to deriving !!(false-y) => false and !!(truth-y) => true . 这是否定TTL导致导出!!(false-y) => false!!(truth-y) => true

A         !A      !(!A)
false-y   true    false
truth-y   false   true

1 In JavaScript the false-y values are false 0, "", null, undefined, NaN. 1在JavaScript中,false-y值为false 0,“”,null,undefined,NaN。 While everything else is truth-y. 虽然其他一切都是真实的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM