从 Google Chrome 控制台:
var x = null;
undefined
x > 0
false
x < 0
false
x > -1
true
x < 1
true
x == 1
false
x === 1
false
最佳答案
当您将 null 与 0 进行相等性比较时,结果为 false。如果你强制null
在数字上下文中进行解释,然后将其视为 0,结果变为 true。
您可以通过输入 +
强制它为数字在前面,或使用像 <
这样的数字运算符, <=
, >
, 和 >=
.注意如何 null >= 0
和 null <= 0
都是真的。
> null == 0
false
> +null == 0
true
> null >= 0
true
> null <= 0
true
ECMAScript Language Specification定义何时执行所谓的“ToNumber”转换。如果是,则 null 和 false 都转换为 0。
§9.1 Type Conversion and Testing:
Table 14 — To Number Conversions
Argument Type Result ------------- ------ Undefined Return NaN Null Return +0 Boolean Return 1 if argument is true. Return +0 if argument is false. Number Return argument (no conversion). String See grammar and note below.
知道何时应用 ToNumber 转换取决于相关运算符。对于关系运算符 <
, <=
, >
, 和 >=
见:
§11.8.5 The Abstract Relational Comparison Algorithm:
The comparison
x < y
, where x and y are values, produces true, false, or undefined (which indicates that at least one operand is NaN). Such a comparison is performed as follows:
Call ToPrimitive(x, hint Number).
Call ToPrimitive(y, hint Number).
If Type(Result(1)) is String and Type(Result(2)) is String, go to step 16. (Note that this step differs from step 7 in the algorithm for the addition operator + in using and instead of or.)
Call ToNumber(Result(1)).
Call ToNumber(Result(2)).
==
运营商不同。它的类型转换描述如下。请注意 null 和 false 如何遵循不同的规则。
§11.9.3 The Abstract Equality Comparison Algorithm
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
1. If Type(x) is different from Type(y), go to step 14.
...
14. If x is null and y is undefined, return true.
15. If x is undefined and y is null, return true.
16. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
17. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
18. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
19. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
20. If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
21. If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
22. Return false.
如果你仔细阅读,你就会明白为什么 false == 0
是真的但是null == 0
是假的。
false == 0
, Type(x) 是 bool 值。这意味着应用步骤 18 的类型转换,并将 false 转换为数字。 ToNumber(false) 为 0,并且0 == 0
为真,所以比较成功。null == 0
, Type(x) 为 Null。没有任何类型检查匹配,因此比较会进入第 22 步,返回 false。比较失败。
关于javascript - 为什么JavaScript中的null大于-1,小于1,但不等于(==)0?那到底是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407544/