为什么 [NaN].includes(NaN) 在 JavaScript 中返回 true? [英] Why does [NaN].includes(NaN) return true in JavaScript?

查看:36
本文介绍了为什么 [NaN].includes(NaN) 在 JavaScript 中返回 true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉 NaN 是奇怪的";在 JavaScript 中,即 NaN === NaN 总是返回 false,如


其他资源:

I'm familiar with NaN being "weird" in JavaScript, i.e., NaN === NaN always returns false, as described here. So one should not make === comparisons to check for NaN, but use isNaN(..) instead.

So I was surprised to discover that

> [NaN].includes(NaN)
true

This seems inconsistent. Why have this behavior?

How does it even work? Does the includes method specifically check isNaN?

解决方案

According to MDN's document say that

Note: Technically speaking, includes() uses the sameValueZero algorithm to determine whether the given element is found.

const x = NaN, y = NaN;
console.log(x == y); // false                -> using ‘loose’ equality
console.log(x === y); // false               -> using ‘strict’ equality
console.log([x].indexOf(y)); // -1 (false)   -> using ‘strict’ equality
console.log(Object.is(x, y)); // true        -> using ‘Same-value’ equality
console.log([x].includes(y)); // true        -> using ‘Same-value-zero’ equality


More detailed explanation:

  1. Same-value-zero equality similar to same-value equality, but +0 and −0 are considered equal.
  2. Same-value equality is provided by the Object.is() method: The only difference between Object.is() and === is in their treatment of signed zeroes and NaNs.


Additional resources:

这篇关于为什么 [NaN].includes(NaN) 在 JavaScript 中返回 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆