The entries() method in JavaScript returns a new Array Iterator object that contains the key/value pairs for each index in the array. This iterator can be used to loop through the array and access both the index and the corresponding value at that index.
Syntax
array.entries();
Return Value
Return Type | Description |
---|---|
Array Iterator | An iterator object that contains key/value pairs for each index in the array. |
Example 1: Using entries() to Iterate Over Array Elements
This code demonstrates how to use the entries() method to iterate over the elements of an array and log the index and value of each element to the console.
let arr = ['a', 'b', 'c']; let iterator = arr.entries(); for (let entry of iterator) { console.log(entry); }
Output:
[0, 'a']
[1, 'b']
[2, 'c']
Example 2: Using entries() with Spread Operator
This code demonstrates how to use the entries() method in combination with the spread operator (…) to convert the iterator object into an array of key/value pairs.
let arr = ['a', 'b', 'c']; let iterator = arr.entries(); let entriesArray = [...iterator]; console.log(entriesArray);
Output:
[[0, 'a'], [1, 'b'], [2, 'c']]
Example 3: Using entries() with forEach() Methods
This code demonstrates how to use the entries() method with the forEach() method to iterate over the key/value pairs in the iterator object and log them to the console.
let arr = ['a', 'b', 'c']; let iterator = arr.entries(); iterator.forEach(entry => { console.log(entry); });
Output:
[0, 'a']
[1, 'b']
[2, 'c']
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
69 | 79 | 62 | 56 | 12 |