我正在浏览 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:
- If Type(x) is different from Type(y), return false.
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.
Return SameValueNonNumber(x, y).
它与 ===
测试基本相同,除了当 x
和 y
都是 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/