<分区>
我正在学习 includes() 功能,我找到了这段代码
[NaN].includes(NaN)//真
但是
NaN === NaN//假
为什么这是可能的?
<分区>
我正在学习 includes() 功能,我找到了这段代码
[NaN].includes(NaN)//真
但是
NaN === NaN//假
为什么这是可能的?
最佳答案
使用相等 NaN === NaN
和使用 include [NaN].includes(NaN)
基本上是在问两个不同的问题:
NaN
是一个非晶实体,它描述了不是数值的概念,实际上没有可以比较的值。平等使用 Strict Equality Comparison , 并定义了 x === y
与等式任一侧的 NaN
的比较始终为 false
:
a. If x is NaN, return false.
b. If y is NaN, return false.
但是,要在数组中搜索 NaN
,并保持 to Array#includes 只传递一个参数而不是回调的签名,我们需要一种方法来“命名”什么我们正在寻找。为了使之成为可能,根据 ECMAScript 2016 (ECMA-262) docs 中的 Array#includes 定义:
The includes method intentionally differs from the similar indexOf method in two ways. First, it uses the SameValueZero algorithm, instead of Strict Equality Comparison, allowing it to detect NaN array elements. Second, it does not skip missing array elements, instead treating them as undefined.
SameValueZero(x, y)的定义声明比较时:
If x is NaN and y is NaN, return true.
关于javascript - 为什么这个 JavaScript includes() 特性有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46838690/