为什么`null >= 0 &&null <= 0` 但不是`null == 0`? [英] Why `null >= 0 && null <= 0` but not `null == 0`?
问题描述
我必须编写一个例程,如果变量的类型是 number
,它会将变量的值增加 1,如果不是,则将 0 分配给变量,其中变量最初是 null
或 undefined
.
I had to write a routine that increments the value of a variable by 1 if its type is number
and assigns 0 to the variable if not, where the variable is initially null
or undefined
.
第一个实现是 v >= 0 ?v += 1 : v = 0
因为我认为任何不是数字的东西都会使算术表达式为假,但这是错误的,因为 null >= 0
被评估为真.然后我了解到 null
的行为类似于 0,并且以下表达式都被评估为 true.
The first implementation was v >= 0 ? v += 1 : v = 0
because I thought anything not a number would make an arithmetic expression false, but it was wrong since null >= 0
is evaluated to true. Then I learned null
behaves like 0 and the following expressions are all evaluated to true.
null >= 0 &&null <= 0
!(null <0 || null > 0)
null + 1 === 1
1/null === Infinity
Math.pow(42, null) === 1
当然,null
不是 0.null == 0
被评估为假.这使得看似重言式的表达式 (v >= 0 && v <= 0) === (v == 0)
错误.
Of course, null
is not 0. null == 0
is evaluated to false. This makes the seemingly tautological expression (v >= 0 && v <= 0) === (v == 0)
false.
为什么 null
像 0,虽然它实际上不是 0?
Why is null
like 0, although it is not actually 0?
推荐答案
你真正的问题似乎是:
为什么:
null >= 0; // true
但是:
null == 0; // false
真正发生的是大于或等于运算符(>=
),执行类型强制(ToPrimitive
),带有 hint 类型Number
,其实所有的关系运算符都有这个行为.
What really happens is that the Greater-than-or-equal Operator (>=
), performs type coercion (ToPrimitive
), with a hint type of Number
, actually all the relational operators have this behavior.
null
被等号运算符 (==
) 以一种特殊的方式处理.简而言之,它只会强制到undefined
:
null
is treated in a special way by the Equals Operator (==
). In a brief, it only coerces to undefined
:
null == null; // true
null == undefined; // true
false
、''
、'0'
和 []
等值以数字为准类型强制,全部强制为零.
Value such as false
, ''
, '0'
, and []
are subject to numeric type coercion, all of them coerce to zero.
您可以在中查看此过程的内部细节抽象平等比较算法和抽象关系比较算法.
总结:
关系比较:如果两个值都不是 String 类型,则在两者上调用
ToNumber
.这与在前面添加一个+
相同,用于 null 强制为0
.
Relational Comparison: if both values are not type String,
ToNumber
is called on both. This is the same as adding a+
in front, which for null coerces to0
.
相等比较:仅对字符串、数字和布尔值调用 ToNumber
.
Equality Comparison: only calls ToNumber
on Strings, Numbers, and Booleans.
这篇关于为什么`null >= 0 &&null <= 0` 但不是`null == 0`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!