通读 ECMAScript 5.1 specification ,+0
和-0
是区分的。
为什么+0 === -0
的计算结果为true
?
最佳答案
JavaScript 使用 IEEE 754 standard来表示数字。来自 Wikipedia :
Signed zero is zero with an associated sign. In ordinary arithmetic, −0 = +0 = 0. However, in computing, some number representations allow for the existence of two zeros, often denoted by −0 (negative zero) and +0 (positive zero). This occurs in some signed number representations for integers, and in most floating point number representations. The number 0 is usually encoded as +0, but can be represented by either +0 or −0.
The IEEE 754 standard for floating point arithmetic (presently used by most computers and programming languages that support floating point numbers) requires both +0 and −0. The zeroes can be considered as a variant of the extended real number line such that 1/−0 = −∞ and 1/+0 = +∞, division by zero is only undefined for ±0/±0 and ±∞/±∞.
本文包含有关不同表示的更多信息。
因此,从技术上讲,这就是必须区分两个零的原因。
However,
+0 === -0
evaluates to true. Why is that (...) ?
此行为在 section 11.9.6 中明确定义,严格相等比较算法(强调部分是我的):
The comparison
x === y
, wherex
andy
are values, produces true or false. Such a comparison is performed as follows:(...)
If Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is −0, return true.
- If x is −0 and y is +0, return true.
- Return false.
(...)
(顺便说一句,+0 == -0
也是如此。)
从逻辑上看,将+0
和-0
视为相等。否则,我们必须在代码中考虑到这一点,而我个人不想这样做;)
注意:
ES2015引入了新的比较方法,Object.is
。 Object.is
明确区分 -0
和 +0
:
Object.is(-0, +0); // false
关于javascript - +0和-0一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42686556/