← 中文资源

简体中文版本

includes 找得到 indexOf 漏掉的 NaN

indexOf 用严格相等查找,NaN === NaN 为 false 所以永远返回 -1;includes 用 SameValueZero 能找到 NaN,检查坏数据应该用它而不是 indexOf。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

indexOf(NaN): -1
includes(NaN): true
includes(-0 in [0]): true
indexOf(-0 in [0]): 0
set has NaN: true
indexOf(1.5): 0 | includes(1.5): true
includes(NaN, 1): false
dirty has NaN: true
clean has NaN: false

实现说明

演示用的数据放在这几个模块级绑定中:readings、dirty。

使用要点

  • 演示输出是带标签的(indexOf(NaN):、includes(NaN):、includes(-0 in [0]):),每个操作都会留下自己的一行标注。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 跨调用保留的状态放在这些顶层绑定里:readings、dirty。

核心语句

const readings = [1.5, NaN, 2.5];
const dirty = [1, 2, NaN];

代码示例

// indexOf finds elements via strict equality: NaN === NaN is false, so it never finds NaN
const readings = [1.5, NaN, 2.5];
console.log('indexOf(NaN):', readings.indexOf(NaN));
console.log('includes(NaN):', readings.includes(NaN));

// includes uses SameValueZero internally: NaN equals NaN; +/-0 count as equal in both methods
console.log('includes(-0 in [0]):', [0].includes(-0));
console.log('indexOf(-0 in [0]):', [0].indexOf(-0));

// SameValueZero is also the key-matching rule of Set/Map: a Set stores and retrieves NaN
console.log('set has NaN:', new Set([NaN]).has(NaN));

// indexOf still fits "give me the position" lookups of normal values; includes only answers presence
console.log('indexOf(1.5):', readings.indexOf(1.5), '| includes(1.5):', readings.includes(1.5));

// fromIndex starts the search at that position: after skipping the head, NaN no longer hits
console.log('includes(NaN, 1):', [NaN, 1].includes(NaN, 1));

// To check "does the data contain a bad value" use includes, not indexOf(NaN) === -1
const dirty = [1, 2, NaN];
console.log('dirty has NaN:', dirty.includes(NaN));
console.log('clean has NaN:', [1, 2, 3].includes(NaN));