Page 1 of 1

Skip few index in a for…of loop in Javascript

Posted: 26 Nov 2020, 12:41
by Marius
With the good old for loop in Javascript I can do things like:

Code: Select all

for (let i=0; i<bla.length; i+=2){
  //...
}
So for every count, I can skip the index by doing a +2.

How can I do the same in the for…of loop to skip the index?

Code: Select all

for (const [i, element] of bla.entries()) {
  //skip few index...
}

Skip few index in a for…of loop in Javascript

Posted: 26 Nov 2020, 13:59
by MarPlo
You may add an if() statement within the for...of loop, like in the following example (the original index is preserved).

Code: Select all

for (const [i, element] of bla.entries()) {
 if (!(i % 2)) {
    // do something here
 }
}