In this article, you will learn about the javascript Array built-in method Array.prototype.entries()
. How does this method work in javascript?
The Array.prototype.entries()
method is used to return a new array iterator object that contains the key/value pairs for each index in the given array.
This method does not change the original array.
The Array iterator object has a built-in method called next()
which can be used to get the next value from the array iterator object.
Here are some examples of Array.prototype.entries()
:
const arr = ['Java', 'C#', 'Javascript', 'Python'];
// array iterator object that contains
// key-value pairs for each index in the array
const iterator1 = arr.entries();
console.log(iterator1.next().value);
// expected output: Array [0, "Java"]
console.log(iterator1.next().value);
// expected output: Array [1, "C#"]
//Iterating with index and element
for (const [index, element] of arr.entries()) {
console.log(index + ":" + element);
}
/*
Output
------------
"0:Java"
"1:C#"
"2:Javascript"
"3:Python"
*/
// looping through key-value pairs in the array
for (const entry of iterator1) {
console.log(entry);
}
/*
Output
------------
[0, "Java"]
[1, "C#"]
[2, "Javascript"]
[3, "Python"]
*/
I hope this article will help you to understand the javascript Array built-in method Array.prototype.entries()
.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments