null是否为零,未定义为算术表达式上的数字? [英] Is null considered zero and undefined not a number on arithmetic expressions?
问题描述
null
评估为 0
和 undefined
to算术表达式 NaN
?
Is null
evaluated to 0
and undefined
to NaN
on arithmetic expressions?
根据一些测试看来似乎如此:
According to some testing it seems so:
> null + null
0
> 4 + null
4
> undefined + undefined
NaN
> 4 + undefined
NaN
假设这样安全或正确吗? (文档中的引用将是A +)。
Is it safe or correct to assume this? (a quote from a documentation would be A+).
推荐答案
将null计算为0并且未定义算术表达式上的NaN?假设这样安全或正确吗?
Is null evaluated to 0 and undefined to NaN on arithmetic expressions? Is it safe or correct to assume this?
是的,是的。 算术表达式将使用 ToNumber
操作:
Yes, it is. An "arithmetic expression" would use the ToNumber
operation:
Argument Type | Result
--------------+--------
Undefined | NaN
Null | +0
… |
它用于以下算术表达式:
It is used in the following "arithmetic" expressions:
- 前缀 / postfix 递增和递减
- 一元
+
和-
运营商 -
+
operator 如果两个参数都不是字符串 - 减法,乘法,除法和模数操作
- relational 运算符如果不是两个参数都是字符串
- prefix/postfix increment and decrement
- the unary
+
and-
operators - the
+
operator if none of the two arguments is a string - subtraction, multiplication, division and modulo operation
- relational operators if not both arguments are strings
相等运算符,所以 null == 0
是假的(并且 null!== 0
无论如何)!
It is not used by the equality operators, so null == 0
is false (and null !== 0
anyway)!
这篇关于null是否为零,未定义为算术表达式上的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!