JavaScript 稀疏数组里,为什么 find() 和 some() 判断 undefined 的结果不同?

作者:青柠时间:2026-12-01浏览:266

用同一个稀疏数组对比 find()、findIndex() 和 some(),判断索引是空槽还是显式存了 undefined。

任务队列有三个位置,中间放了一条草稿。如果要找一个空位,能不能直接判断 value === undefined?把这条判断分别交给 find() 和 some(),你会得到两个看起来对不上的结果。

为什么一个匹配到了,另一个没有

new Array(3) 将数组长度初始化为 3。在向索引 1 写入数据后,索引 0 和 2 仍保持为空槽(hole)。以下示例基于一个前提:数组原型链上不存在任何数字索引属性。

{
  const slots = new Array(3);
  slots[1] = 'draft';
  const isUndefined = (value) => value === undefined;

  console.log('find:', slots.find(isUndefined));
  console.log('findIndex:', slots.findIndex(isUndefined));
  console.log('some:', slots.some(isUndefined));
  console.log('own index 0:', Object.hasOwn(slots, 0));
}
预期控制台显示 find 得到 undefined,findIndex 得到 0,some 得到 false,索引 0 没有自有属性
第一段代码的预期控制台输出。

单独观察 find() 的返回值存在歧义:无论匹配到 undefined 值还是完全未找到,结果均为 undefined。结合 findIndex() 分析可知,其返回值为 0,表明判断函数在首个位置即判定为匹配。

find() 和 findIndex() 每走到一个索引就取值,再把值交给判断函数,匹配后立即停止。some() 会先检查索引属性是否存在,查不到就跳过。因此在这一组数据里,它只用 'draft' 调了一次判断函数。

索引 0 的两种查找路径,find 与 findIndex 取值后调用判断函数,some 查不到属性就前往下一个索引
原型链上也查不到索引 0 时,这两条路径在回调前就分开了。

区分空槽与显式赋值,需检测索引本身

即使向索引 2 显式赋值为 undefined,直接读取索引 0 与索引 2 得到的值依然相同。若要区分二者,可借助 findIndex() 获取索引,并结合 Object.hasOwn() 进行自有属性检查。

{
  const slots = new Array(3);
  slots[1] = 'draft';
  slots[2] = undefined;

  const firstHole = slots.findIndex((_, i) => !Object.hasOwn(slots, i));
  const firstStoredUndefined = slots.findIndex(
    (value, i) => Object.hasOwn(slots, i) && value === undefined,
  );

  console.log('first hole:', firstHole);
  console.log('first stored undefined:', firstStoredUndefined);
  console.log('some:', slots.some((value) => value === undefined));
}
预期控制台显示第一个空槽在 0,第一个显式 undefined 在 2,some 得到 true
第二段代码的预期控制台输出。

这次第一个空槽仍在索引 0,显式存着 undefined 的位置是索引 2。some() 在索引 2 调用判断函数,匹配后返回 true。

队列该用哪一种判断

如果空位指的是数组自身没有这个索引,就用 Object.hasOwn() 检查。它只看数组自身,取值和 some() 的属性存在检查都能看到继承来的属性。拿到 findIndex() 的结果后,用 index === -1 判断是否没找到。索引 0 也是有效结果。

作者最新文章
相关文章
更多