entries() 返回 Array Iterator 对象,按索引升序产出 [index, value] 二元数组,支持 for...of、Array.from 和扩展运算符,但不可用于类数组对象。

entries() 返回的是什么类型的迭代器
entries() 是数组的内置方法,调用后返回一个 Array Iterator 对象,它按索引升序逐个产出 [index, value] 形式的二元数组。这不是普通对象,不能直接用 for...in 遍历,也不能解构赋值到单个变量里而不加括号。
常见错误现象:for (const item of arr.entries()) { console.log(item); } 输出的是 [0, "a"]、[1, "b"] 这样的数组,如果误以为是对象而写成 item.key 或 item.value,会得到 undefined。
正确解构 entries() 的每一项
必须用数组解构语法匹配产出的二元数组结构。最常用写法是:
for (const [index, value] of arr.entries()) {
console.log(index, value);
}
其他合法但不推荐的写法包括:
-
for (const pair of arr.entries()) { const [i, v] = pair; }—— 多一层解构,冗余 -
const iter = arr.entries(); console.log(iter.next().value);—— 手动调用next(),仅在需要中断或条件推进时才用
注意:不能写成 for (const {0: i, 1: v} of arr.entries()),对象解构不支持数字属性名直接展开(除非先转为对象,但没必要)。
entries() 和 for...of / Array.from / 扩展运算符的兼容性
entries() 返回的迭代器可被所有原生支持迭代协议的语法消费,包括:
-
for...of循环(最常用) -
Array.from(arr.entries())→ 得到[[0,a], [1,b], ...]数组,适合需要缓存全部键值对的场景 -
[...arr.entries()]→ 效果同上,但更简洁
性能提示:如果只遍历一次且不需要索引以外的信息,for...of + 解构是最轻量的方式;若后续还要多次读取,用 Array.from() 转成数组更稳妥,因为 entries() 迭代器只能消费一次。
entries() 在稀疏数组和类数组对象上的行为差异
对真实数组(包括含 undefined 或空位的稀疏数组),entries() 仍会为每个索引位置产出一项,空位也会表现为 [index, undefined]。
但它**不适用于类数组对象**(如 arguments、NodeList),这些对象没有 entries 方法。想对它们做类似操作,得先转成数组:
for (const [i, el] of Array.from(document.querySelectorAll('div')).entries()) {
// 安全
}
或者用 Array.prototype.entries.call(nodeList),但可读性差,不建议。

















