为什么[NaN] .includes(NaN)在JavaScript中返回true? [英] Why does [NaN].includes(NaN) return true in JavaScript?
本文介绍了为什么[NaN] .includes(NaN)在JavaScript中返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我熟悉 NaN
是怪异"的,在JavaScript中,即 NaN === NaN
始终返回 false
,如
其他资源:
- 在JavaScript比较中应使用哪个equals运算符(== vs ===)?
- Array.prototype.includes与Array.prototype.indexOf
- +0和-0是否相同?
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 thesameValueZero
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:
- Same-value-zero equality similar to same-value equality, but +0 and −0 are considered equal.
- 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:
- Which equals operator (== vs ===) should be used in JavaScript comparisons?
- Array.prototype.includes vs. Array.prototype.indexOf
- Are +0 and -0 the same?
这篇关于为什么[NaN] .includes(NaN)在JavaScript中返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文