The entries() method of the Array class in JavaScript returns a new array iterator object that contains the key/value pairs for each index in the array.
The syntax of Array.entries() method is:
entries()
This entries() method of Array returns a new array iterator object that contains the key/value pairs for each index in an array.
Array.entries() returns value of type Iterator
.
In JavaScript, we can use the entries() method to iterate over key/value pairs in an array.
For example,
const arr = ['apple', 'banana', 'cherry'];
const iterator = arr.entries();
for (const entry of iterator) {
console.log(entry);
}
[0, 'apple'] [1, 'banana'] [2, 'cherry']
We can use destructuring with entries() method to extract key/value pairs from the iterator.
For example,
const arr = ['apple', 'banana', 'cherry'];
const iterator = arr.entries();
for (const [key, value] of iterator) {
console.log(`Key: ${key}, Value: ${value}`);
}
Key: 0, Value: apple Key: 1, Value: banana Key: 2, Value: cherry
In this JavaScript tutorial, we learned about entries() method of Array: the syntax and few working examples with output and detailed explanation for each example.