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()
与 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()
方法读取 this
的 length
属性,然后生成 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