JavaScript 稀疏数组里,为什么 find() 和 some() 判断 undefined 的结果不同?
用同一个稀疏数组对比 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 值还是完全未找到,结果均为 undefined。结合 findIndex() 分析可知,其返回值为 0,表明判断函数在首个位置即判定为匹配。
find() 和 findIndex() 每走到一个索引就取值,再把值交给判断函数,匹配后立即停止。some() 会先检查索引属性是否存在,查不到就跳过。因此在这一组数据里,它只用 'draft' 调了一次判断函数。

区分空槽与显式赋值,需检测索引本身
即使向索引 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() 在索引 2 调用判断函数,匹配后返回 true。
队列该用哪一种判断
如果空位指的是数组自身没有这个索引,就用 Object.hasOwn() 检查。它只看数组自身,取值和 some() 的属性存在检查都能看到继承来的属性。拿到 findIndex() 的结果后,用 index === -1 判断是否没找到。索引 0 也是有效结果。
JS实现数字转中文读数:处理零与单位映射的通用函数
2026-12-01
默认参数里的回调,为什么读不到函数体改过的值?
2026-12-01
JS数组末尾添加元素:push方法用法与返回值误区
2026-12-01
JS用day.js计算时间差比原生Date好在哪里
2026-12-01
Array.from() 为什么只拿到一行,明明 length 是 2?
2026-12-01



