【问题标题】:Negatives in underscore.js: why is _isEqual(0, -1 * 0) returning false?underscore.js 中的否定:为什么 _isEqual(0, -1 * 0) 返回 false?
【发布时间】:2012-02-26 16:33:04
【问题描述】:

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

0 === -1 * 0
> true

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

这令人惊讶,至少对我而言。我预计=== 为真的两个值将导致_.isEqual 也为真。

这里发生了什么?谢谢!

【问题讨论】:

    标签: javascript integer underscore.js


    【解决方案1】:

    已经明确提出in the source:

    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 differently,但您通常看不到这一点,因为0 == -00 === -0。只有a few ways可以检查差异。

    【讨论】:

    • 谢谢!对我来说,这似乎是一个不明显的设计决定,因为=== 几乎总是能很好地满足我的需求。但我明白了。
    【解决方案2】:

    查看eq 函数here 的源代码。根据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;
    

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2015-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多