javascript - +0和-0一样吗?

标签 javascript

通读 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, where x and y are values, produces true or false. Such a comparison is performed as follows:

(...)

  • If Type(x) is Number, then

    1. If x is NaN, return false.
    2. If y is NaN, return false.
    3. If x is the same Number value as y, return true.
    4. If x is +0 and y is −0, return true.
    5. If x is −0 and y is +0, return true.
    6. Return false.

(...)

(顺便说一句,+0 == -0 也是如此。)

从逻辑上看,将+0-0 视为相等。否则,我们必须在代码中考虑到这一点,而我个人不想这样做;)

<小时/>

注意:

ES2015引入了新的比较方法,Object.isObject.is 明确区分 -0+0:

Object.is(-0, +0); // false

关于javascript - +0和-0一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42686556/

相关文章:

javascript - 使用 moment 抓取不同时区的日期的部分内容

javascript - 使用从一种方法到另一种方法的变量

javascript - jquery 添加小数

javascript - 如何在我的 ejs 文件中包含 Bootstrap 文件?

javascript - 拖放区 : display current filename during upload

javascript - 如何使用 Cypress 断言页面不会重新加载

Javascript:将var中的文本解析为一个集合

javascript - 将 pointerenter 和 pointerleave 事件监听器添加到 map /容器?

java - Android 应用中的 HTML/JS 应用

javascript - 使用 React/Javascript 在 WordPress API 中按 ID 获取选定的多个帖子/页面