此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
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 2015年7月.
entries() 方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键/值对。
In this article
尝试一下
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() 方法读取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> |