The entries()
method in JavaScript is used to return a new Array Iterator
object that contains the key/value pairs for each index in the array. This method is typically used in conjunction with the for...of
loop to iterate over the elements of an array.
Here is an example of how the entries()
method works:
const array1 = ['apple', 'banana', 'orange'];
const iterator = array1.entries();
for (const [index, element] of iterator) {
console.log(`The element at index ${index} is ${element}.`);
}
// the output will be:
// The element at index 0 is apple.
// The element at index 1 is banana.
// The element at index 2 is orange.
In the code example above, we first declare an array called array1
that contains three strings: apple
, banana
, and orange
. We then use the entries()
method to create a new Array Iterator
object that contains the key/value pairs for each index in the array. We then use a for...of
loop to iterate over the elements of the iterator
object, and for each iteration, we log a message to the console that includes the index and element of the current iteration.
As you can see, the entries()
method allows us to easily iterate over the elements of an array and access both the index and element of each element. This can be useful when we need to perform operations on each element in an array, and we want to keep track of the index of each element.
Leave a Reply