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 September 2016.
Array
实例的 keys()
方法返回一个新的 数组迭代器 对象,其中包含数组中每个索引的键。
¥The keys()
method of Array
instances returns a new array iterator object that contains the keys for each index in the array.
Try it
语法
参数
返回值
描述
¥Description
当在 稀疏数组 上使用时,keys()
方法会迭代空槽,就好像它们具有值 undefined
一样。
¥When used on sparse arrays, the keys()
method iterates empty slots as if they have the value undefined
.
keys()
方法是 generic。它只期望 this
值具有 length
属性和整数键控属性。
¥The keys()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
示例
在稀疏数组上使用 keys()
¥Using keys() on sparse arrays
与 Object.keys()
不同,Object.keys()
只包含数组中实际存在的键,keys()
迭代器不会忽略代表缺失属性的漏洞。
¥Unlike Object.keys()
, which only includes keys that actually exist in the array, the keys()
iterator doesn't ignore holes representing missing properties.
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()
¥Calling keys() on non-array objects
keys()
方法读取 this
的 length
属性,然后生成 0 到 length - 1
之间的所有整数索引。实际上没有发生索引访问。
¥The keys()
method reads the length
property of this
and then yields all integer indices between 0 and length - 1
. No index access actually happens.
const arrayLike = {
length: 3,
};
for (const entry of Array.prototype.keys.call(arrayLike)) {
console.log(entry);
}
// 0
// 1
// 2
规范
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.keys |
浏览器兼容性
BCD tables only load in the browser