javascript - 同值零算法如何工作?

标签 javascript ecmascript-6 maps

我正在浏览 Javascript.info 中的 map 章节,并且有一个指向 SameValueZero 算法的链接。谁能用简单的语言解释一下该算法是如何工作的。

我尝试浏览链接但找不到任何内容。

最佳答案

参见 specification :

The internal comparison abstract operation SameValueZero(x, y), where x and y are ECMAScript language values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is different from Type(y), return false.
  2. If Type(x) is Number, then

    • If x is NaN and y is NaN, return true.

    • If x is +0 and y is -0, return true.

    • If x is -0 and y is +0, return true.

    • If x is the same Number value as y, return true.

    • Return false.

  3. Return SameValueNonNumber(x, y).

它与 === 测试基本相同,除了当 xy 都是 NaN,他们也通过了测试。你可以这样实现它:

const sameValueZero = (x, y) => x === y || (Number.isNaN(x) && Number.isNaN(y));

console.log(sameValueZero(0, 0));
console.log(sameValueZero(0, 1));
console.log(sameValueZero(0, NaN));
console.log(sameValueZero(NaN, NaN));

关于javascript - 同值零算法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56195369/

相关文章:

c++ - 如何在 Qt 中使用 HERE api 显示 map ?

javascript - 有没有办法判断 gzip 实际上是否在压缩特定文件?

c# - 从代码后面输出Javascript时如何处理换行符

javascript - JS 检查数值属性是否存在

AngularJS 2.0 编译成 ES6

javascript - 谷歌地图信息框显示上次点击的位置

javascript - Node.js 事件应用程序

javascript - 对象字面量内的类

javascript - 在 ES6 中处理 undefined variable 或属性