JavaScript中null与0的比较:为什么null>=0为真而null==0为假

作者:纸飞机时间:2026-10-21 22:32:38浏览:568

本文深入解析JavaScript中null与0的比较行为。通过对比关系运算符(>=)和相等运算符(==)在ECMAScript规范中的不同处理逻辑,解释为何null>=0返回true而null==0返回false。文章指出这是设计上的差异,建议开发者在代码中显式处理类型检查以避免歧义。

在JavaScript语言中,存在一个令人困惑的现象:表达式 null >= 0 的运算结果为 true,而 null == 0 的运算结果却是 false。本文将详细解析 null 值的比较机制。

前言:null与0的比较现象

1.前言

近期,开发者社区中有人讨论 null 是否等于 0 的问题。

为了验证这一观点,我编写了相应的测试代码进行实验。


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MR_LP:3206064928</title>
</head>
<body>

</body>
<script type="text/javascript">
  console.log(null > 0);   // false
  console.log(null < 0);   // false
  console.log(null >= 0);   // true
  console.log(null <= 0);   // true
  console.log(null == 0);   // false
  console.log(null === 0);    // false
</script>
</html>

结果令人意外。

为什么 console.log(null <= 0) 和 console.log(null >= 0) 的判断结果均为 true?

查阅资料:ECMAScript规范解析

2.查阅资料

要澄清这一现象,我们需要回顾 ECMAScript Language Specification(HTML版本),即ECMAScript语言规范。

2.1 内部相等性运算算法

首先,我们查看 ES3 规范中关于内部相等性运算的算法实现。


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. 
2. If Type(x) is Undefined, return true. 
3. If Type(x) is Null, return true. 
4. If Type(x) is not Number, go to step 11. 
5. If x is NaN, return false. 
6. If y is NaN, return false. 
7. If x is the same number value as y, return true. 
8. If x is +0 and y is -0, return true. 
9. If x is -0 and y is +0, return true. 
10. Return false. 
11. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false. 
12. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false. 
13. Return true if x and y refer to the same object or if they refer to objects joined to each other (see 13.1.2). Otherwise, return false. 
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.

2.2 内部关系运算算法

接着,我们查看 ES3 规范中关于内部关系运算的算法实现。


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: 
1. Call ToPrimitive(x, hint Number). 
2. Call ToPrimitive(y, hint Number). 
3. 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.) 
4. Call ToNumber(Result(1)). 
5. Call ToNumber(Result(2)). 
6. If Result(4) is NaN, return undefined. 
7. If Result(5) is NaN, return undefined. 
8. If Result(4) and Result(5) are the same number value, return false. 
9. If Result(4) is +0 and Result(5) is -0, return false. 
10. If Result(4) is -0 and Result(5) is +0, return false. 
11. If Result(4) is +∞, return false. 
12. If Result(5) is +∞, return true. 
13. If Result(5) is -∞, return false. 
14. If Result(4) is -∞, return true. 
15. If the mathematical value of Result(4) is less than the mathematical value of Result(5) — note that these mathematical values are both finite and not both zero — return true. Otherwise, return false. 
16. If Result(2) is a prefix of Result(1), return false. (A string value p is a prefix of string value q if q can be the result of concatenating p and some other string*r*. Note that any string is a prefix of itself, because r may be the empty string.) 
17. If Result(1) is a prefix of Result(2), return true. 
18. Let k be the smallest nonnegative integer such that the character at position k within Result(1) is different from the character at position k within Result(2). (There must be such a k, for neither string is a prefix of the other.) 
19. Let m be the integer that is the code point value for the character at position k within Result(1). 
20. Let n be the integer that is the code point value for the character at position k within Result(2). 
21. If m < n, return true. Otherwise, return false.

2.3 ES3 的 运算符

2.3.1 ES3 的 “>” 运算符:


The Greater-than Operator ( > ) 
The production RelationalExpression : 
RelationalExpression > ShiftExpression is evaluated as follows: 
1. Evaluate RelationalExpression. 
2. Call GetValue(Result(1)). 
3. Evaluate ShiftExpression. 
4. Call GetValue(Result(3)). 
5. Perform the comparison Result(4) < Result(2). 
6. If Result(5) is undefined, return false. Otherwise, return Result(5).

2.3.2 ES3 的”>=” 运算符:


The Greater-than-or-equal Operator ( >= ) 
The production RelationalExpression : 
RelationalExpression >= ShiftExpression is evaluated as follows: 
1. Evaluate RelationalExpression. 
2. Call GetValue(Result(1)). 
3. Evaluate ShiftExpression. 
4. Call GetValue(Result(3)). 
5. Perform the comparison Result(2) < Result(4). (see 11.8.5). 
6. If Result(5) is true or undefined, return false. Otherwise, return true.

2.3.3 ES3 的 “==” 运算符 :


The Equals Operator ( == ) 
The production EqualityExpression : 
EqualityExpression == RelationalExpression is evaluated as 
follows: 
1. Evaluate EqualityExpression. 
2. Call GetValue(Result(1)). 
3. Evaluate RelationalExpression. 
4. Call GetValue(Result(3)). 
5. Perform the comparison Result(4) == Result(2). (see 11.9.3). 
6. Return Result(5).

规范分析:关系与相等运算符的差异

3. 根据资料得出的内容

重点关注上述规范中加粗强调的部分,我们可以明确以下三点。

  1. 关系运算符与相等运算符不属于同一类别。
  2. 关系运算符在设计上,总是尝试将运算元转换为 number 类型;而相等运算符在设计上,并未做此考虑。
  3. 最重要的一点,不要想当然地将 a > b 和 a == b 的结果与 a >= b 建立联系。符合最初设计思想的正确对应关系是:a > b 与 a >= b 是一组,而 a == b 与其他相等运算符(如 a === b、a != b、a !== b)是一组。

基于此,我们可以反向审视这个问题。


null > 0   // null 尝试转型为number , 则为0 . 所以结果为 false, 
null >= 0  // null 尝试转为number ,则为0 , 结果为 true. 
null == 0  // null在设计上,在此处不尝试转型. 所以 结果为false. 

这里引用 Franky 的观点。

a >= b 运算符只是简单地对 a < b 的结果取反。我认为这是设计失误的另一个理由是:undefined 在标准中被单独列出。细心的读者可能已发现,对于 undefined 的设计,undefined > 0、undefined < 0 和 undefined == 0 的结果符合设计逻辑的一致性。而 null 是被遗漏的部分。直到今天早上,我重新翻阅了 ES3 和 ES5 的相关章节,才恍然大悟自己未从根本上理解该问题。

虽然前面的例子让我捕捉到了 Brendan Eich 当初的设计思想,但从全局角度看,从关系运算符到相等运算符,尤其是相等运算符的设计,显得十分混乱。Brendan Eich 在信中坦言,他对 == 的现状感到无奈,甚至用“愚蠢”形容自己当初的实现(当然,他提到当时仅用10天设计出JS并通过QA测试用例)。即便如此,他表示 null == 0 的结果是他想要的。

至此,我也感到无力。纵观JavaScript,对关系运算和相等运算的设计,除了“混乱”,我想不出更恰当的词。这一点从生产环境代码中大量存在的类型检查和防御性代码即可证明。

同时,Franky 还举了另一个例子。


function case1(a){
  if(a == null){
     ....
  }
} 
 
function case2(a){
  if(a == undefined){
    ...
  }  
}
 
// 上面两组完全等价, 这就是一种不明确表述.
// 我们永远不知道代码编写者的目的到底是同时匹配null 和 undefined还是只匹配其中某一个
 
 
function case3(a){
  if(a === null || a === undefined){
    ...
  }
}
 
// case3 才是最好的表述. 我们明确知道代码编写者的意图. 
// 即使很多人可能认为这个代码很愚蠢. 但我坚定的认为这才是好代码.

最后,不得不提到,在我发出 null >= 0 这封信后,Andrea Giammarchi 表示支持我之前的看法,他认为 null >= 0 的结果应为 false,并建议在 ES7 的严格模式中修改此结果。虽然这同样遭到 David Bruant 的反对。好吧,为我和他这一错误看法默哀一分钟……

后记:设计原则与开发建议

4.后记

因此,编写代码和规范时,都应明确表述。即使表述啰嗦,但不会引起歧义或怀疑,这才是一份好的标准、文档或代码。避免歧义和各种混乱不堪的规则,是一门语言最应遵守的设计原则。

最后,希望大家在日常开发中,能够少遇坑。

作者最新文章