ES6的Array.prototype.keys()返回索引迭代器,按升序产出数组数字索引(0,1,2…),遍历所有存在索引(含空槽),产出{value: index, done: false},可用for...of、展开运算符或Array.from消费。

JavaScript 中 ES6 的 Array.prototype.keys() 方法会返回一个**索引迭代器(Iterator)**,它按升序依次产出数组的**数字索引**(0, 1, 2, …),而不是值或键值对。
keys() 返回的是索引迭代器
调用 arr.keys() 不会立即执行遍历,而是返回一个可迭代对象,该对象实现了 Symbol.iterator,每次调用 .next() 都返回形如 { value: index, done: false } 的对象。
- 它只遍历“存在”的索引(包括空槽,即稀疏数组中的缺失项也会被计入索引位置)
- 不关心元素是否为
undefined或null,只看索引是否存在 - 不会跳过空位(例如
[1, , 3]的keys()仍产出0, 1, 2)
常用获取方式:for...of、展开运算符、Array.from
你可以用标准迭代方式消费这个索引迭代器:
-
for...of 循环:
const arr = ['a', 'b', 'c'];
for (const index of arr.keys()) {
console.log(index); // 0, 1, 2
} -
展开成数组:
const indices = [...arr.keys()]; // [0, 1, 2] -
转为数组(兼容旧写法):
const indices = Array.from(arr.keys()); // [0, 1, 2]
和 entries()、values() 的区别要分清
三者都返回迭代器,但产出内容不同:
立即学习“Java免费学习笔记(深入)”;
-
arr.keys()→ 索引(number) -
arr.values()→ 元素值(any) -
arr.entries()→[index, value]数组(Array<2>)
例如:[10, 20].entries() 产出 {value: [0, 10], done: false},而 .keys() 只产出 {value: 0, done: false}。
注意:keys() 不是 Array.from 的替代品
Array.from(arr.keys()) 虽能拿到索引数组,但它本质是「先创建迭代器再收集」,性能略低于直接用 Array.from({length: arr.length}, (_, i) => i)(尤其对大数组)。但语义更清晰、更符合意图——明确表达“我要所有合法索引”。


















