entries()方法返回一个Array Iterator对象,该对象包含数组中每个索引的键值对,如[0, "Banana"],可通过for...of或next()遍历,不修改原数组。

JavaScript 中数组的 entries() 方法返回一个可迭代对象,它按索引顺序生成 [index, element] 形式的键值对(即数组索引为键,对应元素为值),可用于遍历数组的“键值对结构”。
entries() 返回的是什么?
arr.entries() 不直接返回数组,而是返回一个 迭代器对象,每次调用 .next() 会返回形如 { value: [index, element], done: false } 的对象。实际使用中通常配合 for...of 循环或展开语法操作:
-
for (const [i, val] of arr.entries()) { ... }—— 最常用、最直观 -
Array.from(arr.entries())—— 转为二维数组,如[[0, 'a'], [1, 'b']] -
[...arr.entries()]—— 同样转为二维数组,更简洁
和 for...in、for...of 的区别在哪?
别混淆三者:
-
for...in遍历数组的可枚举属性名(包括自定义属性、继承属性),不保证顺序,且可能遍历到非数字键(如arr.foo = 'bar') -
for...of遍历数组的元素值(val),不提供索引 -
entries()提供的是索引 + 值的配对,语义清晰,专为“键值对式遍历”设计,且只遍历有效索引(稀疏数组中空位也会返回[index, undefined])
实用示例:带索引的处理场景
比如需要在遍历时同时使用下标和值(替代传统 for (let i = 0; i ):
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
立即学习“Java免费学习笔记(深入)”;
✅ 推荐写法(语义明确、安全):
const colors = ['red', 'green', 'blue'];
for (const [i, color] of colors.entries()) {
console.log(`Index ${i}: ${color}`);
}
// 输出:
// Index 0: red
// Index 1: green
// Index 2: blue
⚠ 注意:稀疏数组中,entries() 仍会为“空槽位”生成条目(索引存在但值为 undefined):
const arr = ['a', , 'c']; // 索引 1 是空位 console.log([...arr.entries()]); // → [[0, 'a'], [1, undefined], [2, 'c']]
可以链式配合其他方法吗?
可以,但注意 entries() 返回的是迭代器,不是数组,需先转为数组才能用 map/filter 等:
Array.from(arr.entries()).map(([i, v]) => `${i}-${v}`)-
[...arr.entries()].filter(([i]) => i % 2 === 0)—— 筛选偶数索引项 - 若只需索引或值,也可单独解构:
const indices = [...arr.keys()];或const values = [...arr.values()];

















