Array.prototype.keys()

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

语法

¥Syntax

js
keys()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

新的 可迭代的迭代器对象

¥A new iterable iterator object.

描述

¥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.

示例

¥Examples

在稀疏数组上使用 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.

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()

¥Calling keys() on non-array objects

keys() 方法读取 thislength 属性,然后生成 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.

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看