0

with the good old for loop I can do things like:

for (let i=0; i<bla.length; i+=2){
...
}

So for every count, I can skip the index by doing a +2.

I know for...of is the future but I can't quite figure how to skip the index?

for (const [i, element] of bla.entries()) {
...
}
3
  • 2
    I know for...of is the future Does not mean you have to give up what you already have; You can still do what you want using filter or indexing but at this point it will be like "Swatting flies with a sledgehammer" you can do it but why Commented Nov 26, 2020 at 4:24
  • True, not given up things in the past. Maybe I should rephrase better. I'm learning how to convert from the old for loop to the new for ... of loop. Commented Nov 26, 2020 at 4:30
  • Also it is a good practice to use for of loop when you need to iterate over all the elements; Keep things simple easy to maintain. Commented Nov 26, 2020 at 4:38

1 Answer 1

2

The answer of this depends on whether you would like to preserve the original index, if so, you may add an if statement within the for loop

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

if you don't care about preserving the original index then you may just add a filter before or after entries:

for (const [i, element] of bla.entries().filter((e, i) => !(i % 2))) {
   // do something
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.