Instances an Array iterator: `entries()`
Instances an Array iterator: entries()
The entries()
method in JavaScript instances an iterator object that contains the key/value pairs for each index in the array.
An iterator is a special object that allows you to “navigate” through the elements of the array. It does not directly return an array with all index/value pairs.
It has no input parameters and the syntax is as follows::
Example: basic iteration with index and element
When using entries()
method with for
loop, it’s possible manipulate the index and the item, like this:.
In this case, the entries()
method on the fruits
array is used and then the for
loop is used JavaScript Destructuring.
Example: using a for…of loop
Another example, it’s possible iterate an entries Array with for…of loop, in this way:
In the above example, the entries()
method on the fruits
array is used for memorize the result in a variable called fruitsEntries
which is then used in the for
loop.
Example: sparse arrays
entries()
method will visit empty slots and will consider it as undefined
, in this way:
In this example, first index is empty and for entries()
method the element is undefined
.
The next()
method
After the iterator is created with entries()
method, it possible access the next()
method.
With this method is possible access each element one at a time, in this way:
In the above example, next()
is called twice, this using the first two values of fruitsEntries
.
entries()
for Object and Map
entries()
method is also available for JavaScript Object. It’s similar to Array, in this way:
It’s available also for Map (Map object are collections of key-value pairs), for example:
Notes
- Return on object:
entries()
method return an iterator object that contains the key/value. - Access each element:
next()
method allows the access to elements one at a time. - Available also for other elements:
entries()
method is also available for Object and Map.