We can access array elements using a for-of loop:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
How can I modify this code to access the current index too? I want to achieve this using for-of syntax, neither forEach nor for-in.
We can access array elements using a for-of loop:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
How can I modify this code to access the current index too? I want to achieve this using for-of syntax, neither forEach nor for-in.
in html/js context, on modern browsers, with other iterable objects than Arrays we could also use [Iterable].entries():
Array#entries
returns the index and the value, if you need both:In a
for..of
loop we can achieve this viaarray.entries()
.array.entries
returns a new Array iterator object. An iterator object knows how to access items from an iterable one at the time, while keeping track of its current position within that sequence.When the
next()
method is called on the iterator key value pairs are generated. In these key value pairs the array index is the key and the array item is the value.A
for..of
loop is basically a construct which consumes an iterable and loops through all elements (using an iterator under the hood). We can combine this witharray.entries()
in the following manner:In this world of flashy new native functions, we sometimes forget the basics.
Clean, efficient, and you can still
break
the loop. Bonus! You can also start from the end and go backwards withi--
!For those using objects that are not an
Array
or even array-like, you can build your own iterable easily so you can still usefor of
for things likelocalStorage
which really only have alength
:Then just feed it a number:
the for loop traverses the array, while the indexof property takes the value of the index that matches the array. P.D this method has some flaws with numbers, so use fruits