本文介绍了+0和-0是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读, +区分0 -0

为什么 +0 === -0 评估为 true

推荐答案

JavaScript使用来表示数字。来自:

JavaScript uses IEEE 754 standard to represent numbers. From Wikipedia:

用于浮点运算的IEEE 754标准(目前大多数都使用)支持浮点数的计算机和编程语言需要+0和-0。零可以被认为是扩展实数线的变体,使得1 / -0 =-∞和1 / + 0 = +∞,除以0仅对于±0 /±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 ±∞/±∞.

本文包含有关不同表示形式的更多信息。

The article contains further information about the different representations.

所以从技术上讲,这就是为什么必须区分零。

So this is the reason why, technically, both zeros have to be distinguished.

此行为在,严格的等式比较算法(重点部分是我的):

This behaviour is explicitly defined in section 11.9.6, the Strict Equality Comparison Algorithm (emphasis partly mine):

(...)


  • 如果Type(x)是Number,那么

  • If Type(x) is Number, then


  1. 如果x是NaN,则返回false。

  2. 如果y为NaN,则返回false。

  3. 如果x与y的数字值相同,则返回true。

  4. 如果x为+0,y为-0,返回true。

  5. 如果x为-0且y为+0,则返回true。

  6. 返回false。

  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 顺便说一句。)

(The same holds for +0 == -0 btw.)

从逻辑上讲,处理 +0 -0 相同。否则我们必须在我们的代码中考虑到这一点,我个人不想这样做;)

It seems logically to treat +0 and -0 as equal. Otherwise we would have to take this into account in our code and I, personally, don't want to do that ;)

注意:

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

ES2015 introduces a new comparison method, Object.is. Object.is explicitly distinguishes between -0 and +0:

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

这篇关于+0和-0是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:38