在ECMAScript 5.1规范中,+0和-0是有区别的。
为什么+0 === -0的结果为真?
在ECMAScript 5.1规范中,+0和-0是有区别的。
为什么+0 === -0的结果为真?
当前回答
我将其归咎于严格相等比较方法('===')。 看4d部分
参见7.2.13规范严格相等比较
其他回答
JavaScript使用IEEE 754标准来表示数字。从维基百科:
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 ±∞/±∞.
本文包含关于不同表示形式的进一步信息。
这就是为什么,技术上讲,两个0都要区分。
但是,+0 === -0的结果为true。为什么会这样?
这种行为在第11.9.6节严格相等比较算法中明确定义(重点部分是我的):
比较x === y,其中x和y为值,产生true或false。这样的比较如下: (…) 如果Type(x)是Number,则 如果x为NaN,则返回false。 如果y是NaN,返回false。 如果x与y的Number值相同,则返回true。 如果x为+0,y为−0,则返回true。 如果x为−0,y为+0,则返回true。 返回false。 (…)
(顺便说一句,+0 == -0也是如此。)
把+0和-0视为相等似乎是合乎逻辑的。否则,我们将不得不在我们的代码中考虑到这一点,我个人不想这样做;)
注意:
ES2015引入了一个新的比较方法Object.is。对象。显式区分-0和+0:
Object.is(-0, +0); // false
在JavaScript中用于表示数字类型的IEEE 754标准中,符号由位表示(1表示负数)。
因此,对于每个可表示的数字,包括0,都存在一个负数和一个正数。
这就是-0和+0同时存在的原因。
如果需要支持-0和+0的符号函数:
var sign = x => 1/x > 0 ? +1 : -1;
它就像数学一样。符号,只不过符号(0)返回1而符号(-0)返回-1。
我们可以使用Object。就是区分+0和-0,还有一点,NaN==NaN。
Object.is(+0,-0) //false
Object.is(NaN,NaN) //true
维基百科有一篇很好的文章解释了这一现象:http://en.wikipedia.org/wiki/Signed_zero
简单地说,+0和-0都在IEEE浮点规范中定义。从技术上讲,它们都不同于不带符号的0,后者是整数,但实际上它们的结果都是0,因此在实际应用中,可以忽略这种区别。