简体   繁体   中英

Continue inside a forEach loop

It is standard practice to continue inside a loop if a certain condition is met/unmet. In a Javascript forEach loop, this produces a syntax error:

const values = [1, 2, 3, 4, 5];
values.forEach((value) => {
    if (value === 3) { continue; }
    console.log(value);
})
SyntaxError[ ... ]: Illegal continue statement: no surrounding iteration statement

This happens whether I use function or an arrow function. How can you continue inside a forEach loop?

Obviously, you could do an inverse case ( if (value !== 3) { ... } ), but that is not what I'm looking for.

As @robertklep stated forEach() is not a loop, it is a function. You cannot use the continue keyword inside a forEach loop because its functionality is meant to loop each item in the array.

To achive the simmilar behavior you can use,

  for(let item of values){
     if (item === 3) { 
      continue;
     }
     console.log(item);
  }

For practical purposes, return in a forEach() callback is equivalent to continue in a conventional for loop but it isn't the most idiomatic use of functional programming patterns

To solve that, you can filter before you loop:

const values = [1, 2, 3, 4, 5];
values.filter(v => v !== 3).forEach((value) => {
    console.log(value);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM