In JavaScript, arrays offer a plethora of methods to manipulate and traverse their elements efficiently. One such method is entries()
, which allows you to iterate over the key-value pairs of an array. This method is particularly useful when you need both the index and value of each element. In this article, we’ll delve into the entries()
method, exploring its syntax, functionality, and usage through comprehensive examples.
Syntax:
The syntax of the entries()
method is simple:
array.entries()
Parameters:
This method does not accept any parameters.
Return Value:
A new array iterator object that contains key-value pairs for each index-value pair in the array.
Examples:
Let’s explore the entries()
method with detailed examples:
Example 1:
let fruits = ['apple', 'banana', 'cherry'];
for (const [index, fruit] of fruits.entries()) {
console.log(`${index}: ${fruit}`);
}
/* Output:
0: apple
1: banana
2: cherry
*/
In this example, the entries()
method is used to iterate through the fruits
array, providing both the index and value of each element.
Example 2:
let numbers = [10, 20, 30, 40, 50];
for (const [index, number] of numbers.entries()) {
console.log(`Index ${index}: ${number}`);
}
/* Output:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50
*/
Here, the entries()
method is utilized to loop through the numbers
array, displaying each element along with its corresponding index.
Example 3:
let colors = ['red', 'green', 'blue'];
const iterator = colors.entries();
console.log(iterator.next().value); // Output: [0, 'red']
console.log(iterator.next().value); // Output: [1, 'green']
console.log(iterator.next().value); // Output: [2, 'blue']
console.log(iterator.next().value); // Output: undefined
This example demonstrates how you can use the entries()
method in conjunction with iterators to access the key-value pairs of an array sequentially.