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()
返回值
一个新的可迭代迭代器对象。
描述
示例
迭代索引和元素
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()
方法读取 this
的 length
属性,然后访问每个整数索引。
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® 2026 Language Specification # sec-array.prototype.entries |