array.prototype.keys() 返回索引迭代器而非数组,需用 for...of、展开运算符或 array.from() 消费;其 next() 方法返回 {value: 索引, done: false},不可直接用于 for...in 或 foreach。

JavaScript 中不能对数组直接使用 keys() 方法来“遍历获取索引”,因为 Array.prototype.keys() 返回的是一个**迭代器(Iterator)对象**,不是数组,也不能直接用 for...in 或 forEach 处理——它需要配合 for...of、展开运算符或 Array.from() 等方式消费。
keys() 返回的是索引迭代器
arr.keys() 不返回索引数组,而是返回一个可迭代对象,每次调用 next() 会按顺序产出 { value: 索引, done: false } 形式的对象。例如:
```js
const arr = ['a', 'b', 'c'];
const iterator = arr.keys();
console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
```
常用方式:用 for...of 遍历索引
这是最直观、推荐的方式,适合需要逐个处理索引的场景:
Java项目代码review工具。分析Git变更+完整调用链路上下文,推断业务需求,进行多维度评分和分类汇总,生成完整PRD文档。包含细粒度Java代码审查清单(Null安全、异常处理、Streams、并发、equals/hashCode、资源管理、API设计、性能、MyBatis/ORM、事务边界、SQL/DD...
- 直接用
for...of获取每个索引值 - 索引是纯数字,无需额外转换
```js
const arr = ['apple', 'banana', 'cherry'];
for (const index of arr.keys()) {
console.log(index); // 0, 1, 2
}
```
转成数组后操作:用 Array.from() 或展开运算符
如果需要一次性拿到所有索引(比如想 map、filter 或解构),可转为真实数组:
-
Array.from(arr.keys())→[0, 1, 2] -
[...arr.keys()]→ 同样得到索引数组 - 之后就能用
map()、forEach()等数组方法
```js
const arr = ['x', 'y', 'z'];
const indices = [...arr.keys()];
indices.forEach(i => console.log(`Index ${i} has ${arr[i]}`));
// Index 0 has x
// Index 1 has y
// Index 2 has z
```
注意:不要和 Object.keys() 混淆
Object.keys() 用于对象,返回属性名字符串数组(包括数组的“可枚举属性”,但不包含数字索引);而 Array.prototype.keys() 是数组专属方法,只产出数值索引。两者用途和行为完全不同:
-
Object.keys([10,20])→[](空数组,因数字索引不可枚举) -
[10,20].keys()→ 迭代器,产出0和1
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










