JavaScript(JS) array method - entries
The entries()
method is an array method in JavaScript that returns an iterator object that contains the key-value pairs of each element in the array. The key is the index of the element, and the value is the element itself.
Here's the syntax of the entries()
method:
array.entries();
array
is the array that theentries()
method is called on.
The entries()
method returns an iterator object that contains the key-value pairs of each element in the array. You can use this iterator to loop through the array and access each key-value pair.
Here's an example of how to use the entries()
method:
let array = ['a', 'b', 'c']; let iterator = array.entries(); for (let entry of iterator) { console.log(entry); }
In this example, we have an array array
containing the elements ['a', 'b', 'c']
. We use the entries()
method to create an iterator object that contains the key-value pairs of each element in the array. We then loop through this iterator using a for...of
loop and output each key-value pair to the console. The output of this code is:
[0, 'a'] [1, 'b'] [2, 'c']
This output shows that the entries()
method returns an iterator object that contains an array of two elements for each element in the original array. The first element is the index of the array, and the second element is the value of the array element.
Note that the entries()
method was introduced in ECMAScript 6, so it may not be supported by older browsers.