最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How does same value zero algorithm works? - Stack Overflow

programmeradmin2浏览0评论

I was going through map chapter in Javascript.info and there is a link given to SameValueZero algorithm. Can someone explain how does that algorithm works in simple words.

I tried going through the link but can't find anything.

I was going through map chapter in Javascript.info and there is a link given to SameValueZero algorithm. Can someone explain how does that algorithm works in simple words.

I tried going through the link but can't find anything.

Share Improve this question asked May 18, 2019 at 1:54 Johnny DeppJohnny Depp 1711 silver badge6 bronze badges 3
  • 2 Does this help at all? – Alicia Sykes Commented May 18, 2019 at 2:02
  • Yeah ! great article thnx :) – Johnny Depp Commented May 18, 2019 at 3:10
  • 1 Accept one of your answers, if either of them solved your problem- you will get +2 rep. – Alicia Sykes Commented May 18, 2019 at 3:48
Add a comment  | 

2 Answers 2

Reset to default 18

See the 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).

It's basically the same as a === test, except that when x and y are both NaN, they pass the test as well. You could implement it like this:

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));

Same value zero comparison algorithm (see here why), which is a modified version of the strict equality comparison. The main difference between the two is NaN with NaN equality consideration:

  • Same value zero considers that NaN is equal with NaN
  • Strict equality considers that NaN is not equal with NaN
发布评论

评论列表(0)

  1. 暂无评论