JavaScript entries() 方法
最后修改于 2025 年 4 月 4 日
在本文中,我们将展示如何使用 JavaScript 中的 entries
方法来迭代数组。
使用 entries() 迭代数组
entries
方法返回一个新的 Array Iterator 对象,该对象包含数组中每个索引的键/值对。此方法提供了一种在迭代期间访问数组元素的索引和值的方式。
由 entries
返回的迭代器遵循可迭代协议。这意味着它可以与 for...of
循环和其他使用可迭代对象的结构一起使用。每次迭代返回一个包含两个元素的数组。
第一个元素是索引(键),第二个元素是该索引处的值。当您在处理期间需要数组元素的位置和值时,这特别有用。原始数组保持不变。
基本 entries() 示例
以下示例演示了 entries
方法的基本用法。
const fruits = ['apple', 'banana', 'cherry']; const iterator = fruits.entries(); console.log(iterator.next().value); // [0, 'apple'] console.log(iterator.next().value); // [1, 'banana'] console.log(iterator.next().value); // [2, 'cherry']
我们使用 entries
创建一个数组迭代器,并手动调用 next
来获取每个键/值对。每次调用都会返回一个数组,其中索引 0 是位置,索引 1 是值。
$ node main.js [ 0, 'apple' ] [ 1, 'banana' ] [ 2, 'cherry' ]
将 entries() 与 for...of 循环一起使用
entries
方法与 for...of
循环配合使用效果特别好,可以进行干净的迭代。
const colors = ['red', 'green', 'blue']; for (const [index, color] of colors.entries()) { console.log(`Index ${index} has color ${color}`); }
我们在 for...of
循环中使用数组解构,将索引和值直接分配给变量。这提供了一个清晰的语法,用于在迭代期间访问位置和值。
$ node main.js Index 0 has color red Index 1 has color green Index 2 has color blue
将 entries() 迭代器转换为数组
由 entries
返回的迭代器可以使用展开运算符或 Array.from
转换为数组。
const letters = ['a', 'b', 'c']; const entriesArray = [...letters.entries()]; console.log(entriesArray);
我们使用展开运算符将迭代器转换为数组。生成的数组包含子数组,每个子数组代表原始数组中的一个索引/值对。
$ node main.js [ [ 0, 'a' ], [ 1, 'b' ], [ 2, 'c' ] ]
将 entries() 与稀疏数组一起使用
entries
方法通过在其迭代中包含空槽来处理稀疏数组。
const sparseArray = [1, , 3]; const iterator = sparseArray.entries(); for (const [index, value] of iterator) { console.log(`Index ${index}:`, value); }
我们创建一个带有空槽的稀疏数组,并使用 entries
进行迭代。空槽包含在迭代中,其值为 undefined
。这演示了 entries
如何处理所有数组索引。
$ node main.js Index 0: 1 Index 1: undefined Index 2: 3
将 entries() 与类数组对象一起使用
当通过 Array.prototype.entries.call
调用时,entries
方法可以与类数组对象一起使用。
const arrayLike = { 0: 'first', 1: 'second', length: 2 }; const iterator = Array.prototype.entries.call(arrayLike); console.log([...iterator]);
我们使用 call
将 entries
应用于类数组对象。这演示了如何将数组方法与不是真正数组但具有类似结构的对象一起使用。结果显示了每个属性的键/值对。
$ node main.js [ [ 0, 'first' ], [ 1, 'second' ] ]
来源
在本文中,我们已经演示了如何使用 entries() 方法在 JavaScript 中迭代数组,同时访问索引和值。
作者
列出 所有 JS 数组函数。