The entries() method in JavaScript is used to create a new Array Iterator object that contains key-value pairs for each index-value pair in the array. It returns an iterator, which can be used to loop through the entries of the array.
Syntax: array.entries()
- Return value: An iterator object that contains key-value pairs for each index-value pair in the array.
- Example:
let fruits = ['apple', 'banana', 'orange'];
let iterator = fruits.entries();
for (let entry of iterator)
{
console.log(entry);
}
Output:
[0, 'apple']
[1, 'banana']
[2, 'orange']
In this example:
- We have an array `fruits` containing ['apple', 'banana', 'orange'].
- We use the `entries()` method to create an iterator object `iterator`.
- We iterate over the iterator using a `for...of` loop to log each key-value pair (index-value pair) of the array to the console.
The `entries()` method is useful when you need to iterate over both the indices and values of an array simultaneously, especially in situations where you want to perform operations based on both the indices and values.