试一试
const array = ["a", "b", "c"];
const iterator = array.entries();
console.log(iterator.next().value);
// Expected output: Array [0, "a"]
console.log(iterator.next().value);
// Expected output: Array [1, "b"]
语法
js
entries()
参数
无。
返回值
一个新的可迭代迭代器对象。
描述
当用于稀疏数组时,entries() 方法会将空槽(empty slots)迭代为具有 `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` 属性,然后访问所有键为小于 `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' ]
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-array.prototype.entries |
浏览器兼容性
加载中…