javascript数组的keys()和values()方法返回索引或元素值的迭代器,需用for...of、array.from()或.next()遍历;keys()产出所有合法索引(含空槽),values()跳过空槽产出实际元素值。

JavaScript 数组的 keys() 和 values() 方法会返回迭代器(Iterator),用于遍历数组的索引或元素值。它们不直接返回数组,而是返回一个可迭代对象,需配合 for...of、Array.from() 或手动调用 .next() 使用。
keys():获取索引迭代器
arr.keys() 返回一个遍历数组**索引(从 0 开始)** 的迭代器。
- 索引是数字类型,按升序逐个产出
- 稀疏数组中,
keys()仍会为所有合法索引(包括空槽位置)生成键,例如[1,,3]的keys()产出0, 1, 2
✅ 常用写法:
const arr = ['a', 'b', 'c'];
const keyIter = arr.keys();
<p>for (const index of keyIter) {
console.log(index); // 0, 1, 2
}</p><p>// 或转成数组
console.log(Array.from(arr.keys())); // [0, 1, 2]
</p>
values():获取元素值迭代器
arr.values() 返回一个遍历数组**每个元素值**的迭代器,行为与 for...of 直接遍历数组一致。
- 跳过空槽(在稀疏数组中表现为
undefined,但实际不产出该值) - ES2015+ 默认是数组的默认迭代器,所以
arr[Symbol.iterator] === arr.values
✅ 示例:
const arr = ['x', , 'z']; // 索引 1 是空槽
const valueIter = arr.values();
<p>for (const val of valueIter) {
console.log(val); // 'x', 'z'(跳过了空槽)
}</p><p>console.log([...arr.values()]); // ['x', 'z']
</p>
entries():同时获取索引和值(补充常用项)
虽然不是问题所问,但常与 keys/values 并列使用:arr.entries() 返回 [index, value] 元组的迭代器。
const arr = ['p', 'q'];
for (const [i, v] of arr.entries()) {
console.log(i, v); // 0 'p', 1 'q'
}
手动控制迭代器(进阶用法)
调用 .next() 可逐步取值,返回 { value: ..., done: true/false } 对象:
const iter = ['a', 'b'].values();
console.log(iter.next()); // { value: 'a', done: false }
console.log(iter.next()); // { value: 'b', done: false }
console.log(iter.next()); // { value: undefined, done: true }
注意:迭代器只能单向消耗,不可重用;再次调用 .next() 在耗尽后始终返回 { done: true }。











