[英]Continue inside a forEach loop
It is standard practice to continue
inside a loop if a certain condition is met/unmet.如果满足/未满足某个条件,则在循环内
continue
是标准做法。 In a Javascript forEach
loop, this produces a syntax error:在 Javascript
forEach
循环中,这会产生语法错误:
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.无论我使用
function
还是箭头函数,都会发生这种情况。 How can you continue
inside a forEach
loop?如何在
forEach
循环中continue
?
Obviously, you could do an inverse case ( if (value !== 3) { ... }
), but that is not what I'm looking for.显然,你可以做一个相反的情况(
if (value !== 3) { ... }
),但这不是我想要的。
As @robertklep stated forEach() is not a loop, it is a function.正如@robertklep 所说, forEach() 不是一个循环,它是一个函数。 You cannot use the
continue
keyword inside a forEach loop because its functionality is meant to loop each item in the array.您不能在 forEach 循环中使用
continue
关键字,因为它的功能是循环数组中的每个项目。
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出于实际目的,forEach() 回调中的 return 等效于传统 for 循环中的 continue,但它不是函数式编程模式最惯用的用法
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);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.