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 July 2015.
嘗試一下
const array1 = ["a", "b", "c"];
const iterator1 = array1.entries();
console.log(iterator1.next().value);
// 預期輸出:Array [0, "a"]
console.log(iterator1.next().value);
// 預期輸出: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
屬性,並存取所有鍵為非負整數且小於 length
的屬性。
js
const arrayLike = {
length: 3,
0: "a",
1: "b",
2: "c",
3: "d", // entries() 會忽略此屬性,因為 length 為 3
};
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 |