Skip to content
Advertisement

Is there a way to go back by one iteration in a for-each loop?

For example, if I were to do…

JavaScript

If it isn’t possible, is there another method of traversing through some sort of collection class while controlling the iteration counter? I tried looking through the answers to this question but couldn’t think of a way that was clear to me.

Any suggestions are appreciated!

Advertisement

Answer

It depends on what you are trying to do, but you can use a while-loop and increment the index when it’s appropriate:

JavaScript

Or you can use a for-loop without incrementing the index after each iteration:

JavaScript

Also if the collection implements Iterable, you can use the iterator to iterate over the collection:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement