underscore.js中的否定词:为什么_isEqual(0,-1*0)返回false

Negatives in underscore.js: why is _isEqual(0, -1 * 0) returning false?

本文关键字:false 返回 isEqual js 为什么 underscore      更新时间:2023-09-26

使用javascript库undercore.js(v.1.3.1),我在最新的Chrome(17.0.963.56)和Firefox 7.0中的mac上复制了以下内容:

0 === -1 * 0
> true
_.isEqual(0, -1 * 0)
> false

至少对我来说,这是令人惊讶的。我原以为===为真的两个值会导致_.isEqual也为真。

这是怎么回事?谢谢

它已经明确地放在源中:

function eq(a, b, stack) {
  // Identical objects are equal. `0 === -0`, but they aren't identical.
  // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
  if (a === b) return a !== 0 || 1 / a == 1 / b;

事实上,JavaScript对0-0的解释确实不同,但您通常看不到这一点,因为0 == -00 === -0。只有几种方法可以检查差异。

在此处查看eq函数的源代码。根据isEqual-1 * 0-0,而不是0,因此0-0不相等。

相关线路:

// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;

我以前确实知道这件事,但它会产生一些有趣的邪恶代码

它比这更深。JavaScript使用IEEE双精度浮点数,它们对0和-0有不同的表示形式(这在处理极限等问题时可能很重要)。但通常你不会注意到这一点,因为0==-0。