有人可以告诉我为什么以下代码在JavaScript中返回true?
console.log(true > null); //returns true
null
is like false
in this case, wich is 0
as a number. true
is 1
as a number.
1
is bigger ( >
) than 0
.
They are converted to numbers, null
gives 0
and true
gives 1
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
- Let nx be the result of calling ToNumber( px ). Because px and py are primitive values evaluation order is not important.
- Let ny be the result of calling 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/ ).
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.
If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
From the MDN .
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
代码不正确,您需要这样做:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.