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 May 2018.

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

尝试一下

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

const iterator1 = array1.entries();

console.log(iterator1.next().value);
// Expected output: Array [0, "a"]

console.log(iterator1.next().value);
// Expected output: Array [1, "b"]

语法

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® 2025 Language Specification
# sec-array.prototype.entries

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
entries

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见