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.

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

¥The entries() method of Array instances returns a new array iterator object that contains the key/value pairs for each index in the array.

Try it

语法

¥Syntax

js
entries()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

新的 可迭代的迭代器对象

¥A new iterable iterator object.

描述

¥Description

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

¥When used on sparse arrays, the entries() method iterates empty slots as if they have the value undefined.

entries() 方法是 generic。它只期望 this 值具有 length 属性和整数键控属性。

¥The entries() method is generic. It only expects the this value to have a length property and integer-keyed properties.

示例

¥Examples

使用索引和元素进行迭代

¥Iterating with index and element

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 循环

¥Using a for...of loop

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

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

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

迭代稀疏数组

¥Iterating sparse arrays

entries() 将像 undefined 一样访问空槽。

¥entries() will visit empty slots as if they are undefined.

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

对非数组对象调用 entries()

¥Calling entries() on non-array objects

entries() 方法读取 thislength 属性,然后访问键为小于 length 的非负整数的每个属性。

¥The entries() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length.

js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: "d", // ignored by entries() since length is 3
};
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看