Array.prototype.entries()

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.

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

尝试一下

语法

js
entries()

返回值

描述

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

entries() 方法是通用的。它只要求 this 值具有 length 属性和以整数为键的属性。

示例

迭代索引和元素

js
const a = ["a", "b", "c"];

for (const [index, element] of a.entries()) {
  console.log(index, element);
}

// 0 'a'
// 1 'b'
// 2 'c'

使用 for...of 循环

js
const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}

// [0, 'a']
// [1, 'b']
// [2, 'c']

迭代稀疏数组

entries() 将访问空槽,就像它们是 undefined 一样。

js
for (const element of [, "a"].entries()) {
  console.log(element);
}
// [0, undefined]
// [1, 'a']

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

entries() 方法读取 thislength 属性,然后访问每个整数索引。

js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
};
for (const entry of Array.prototype.entries.call(arrayLike)) {
  console.log(entry);
}
// [ 0, 'a' ]
// [ 1, 'b' ]
// [ 2, 'c' ]

规范

Specification
ECMAScript Language Specification
# sec-array.prototype.entries

浏览器兼容性

BCD tables only load in the browser

参见