Array.prototype.keys()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since May 2018.

keys() 方法返回一个新的数组迭代器对象,其中包含数组中每个索引的键。

尝试一下

const array1 = ["a", "b", "c"];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// Expected output: 0
// Expected output: 1
// Expected output: 2

语法

js
keys()

返回值

描述

当用于稀疏数组时,keys() 方法迭代空槽,就像它们的值为 undefined 一样。

keys() 方法是通用的。它只期望 this 值具有 length 属性和整数键属性。

示例

在稀疏数组中使用 keys()

Object.keys() 只包含数组中实际存在的键不同,keys() 迭代器不会忽略缺失属性的键。

js
const arr = ["a", , "c"];
const sparseKeys = Object.keys(arr);
const denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys); // [0, 1, 2]

在非数组对象上调用 keys()

keys() 方法读取 thislength 属性,然后生成 0 到 length - 1 之间的所有整数索引。实际并不会访问索引。

js
const arrayLike = {
  length: 3,
};
for (const entry of Array.prototype.keys.call(arrayLike)) {
  console.log(entry);
}
// 0
// 1
// 2

规范

Specification
ECMAScript® 2025 Language Specification
# sec-array.prototype.keys

浏览器兼容性

BCD tables only load in the browser

参见