JavaScript 中的负零?

Negative zero in JavaScript?

我刚刚注意到我可以在 JavaScript 中执行以下操作:

var z = -0;
console.log(z); // prints -0

为什么一元取反对零有效?

这是众多 JavaScript 怪癖之一还是它确实(以某种方式)有目的?


P.S.:

这似乎发生在 Firefox 38.0a2 和 Chrome 41.0.2272 上。 Node.js v0.10.36 不会发生。不知道 IE。

您刚刚遇到了 signed zero

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. Real arithmetic with signed zeros can be considered a variant of the extended real number line such that 1/−0 = −∞ and 1/+0 = +∞; division is only undefined for ±0/±0 and ±∞/±∞.

Javascript中的所有数字都是浮点数,因此零必须有符号。

我觉得这不是问题。至少 alert(-0 == 0) returns true。我想如果有一位用于符号,如果值为0,也可以设置该位。但是,它仍然是相同的数字。