[英]Why does (true > null) always return true in JavaScript?
有人可以告诉我为什么以下代码在JavaScript中返回true?
console.log(true > null); //returns true
null
is like false
in this case, wich is 0
as a number. 在这种情况下,
null
与false
类似,数字为0
。 true
is 1
as a number. true
是1
作为数字。
1
is bigger ( >
) than 0
. 1
比0
大( >
)。
They are converted to numbers, null
gives 0
and true
gives 1
它们被转换为数字,
null
给出0
, true
给出1
http://ecma-international.org/ecma-262/5.1/#sec-11.8.5 http://ecma-international.org/ecma-262/5.1/#sec-11.8.5
If it is not the case that both Type( px ) is String and Type( py ) is String, then
如果不是Type( px )都是String而Type( py )是String,那么
- Let nx be the result of calling ToNumber( px ).
设nx是调用ToNumber( px )的结果。 Because px and py are primitive values evaluation order is not important.
因为px和py是原始值,所以评估顺序并不重要。
- Let ny be the result of calling ToNumber( py ).
让ny成为调用ToNumber( py )的结果。
Number(null) //0
Number(true) //1
可能是因为true = 1
,其中null = 0
JavaScript does a lot of type coercion in the background and a lot of the results you'll find aren't useful (see http://wtfjs.com/ ). JavaScript在后台执行了很多类型强制,你会发现很多结果都没用(参见http://wtfjs.com/ )。
In this case, true which is coerced as 1 is greater than null which is coerced to 0. Since 1 is greater than 0 the result is true. 在这种情况下,被强制为1的true大于被强制为0的null。因为1大于0,结果为真。
If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
如果其中一个操作数是布尔值,则布尔操作数如果为真则转换为1,如果为假则转换为+0。
What's happening behind is that the relational operators ( >
in this case) perform type coercion before doing the comparison. 背后发生的是关系运算符(在这种情况下为
>
)在进行比较之前执行类型强制。 When doing the ToPrimitive
, true gets coerced to a 1, and null to a 0. You can check details here of how the operators actually work here 当进行
ToPrimitive
,真正被强制转换为1,和零到0。您可以在这里检查的经营者是如何工作的细节在这里
代码不正确,您需要这样做:
console.log(true > typeof null);
The compare operator ">" forces both it's left and right side to be converted to numbers. 比较运算符“>”强制将其左侧和右侧转换为数字。 Number(true) is 1, Number(null) is 0, so what is in the paranthesis is taken as "1>0", which is always true in result.
Number(true)为1,Number(null)为0,因此paranthesis中的内容被视为“1> 0”,结果中始终为true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.