语法错误:continue 必须在循环内

continue 语句不在循环语句内时,会发生 JavaScript 异常 "continue 必须在循环内"。

¥The JavaScript exception "continue must be inside loop" occurs when a continue statement is not inside a loop statement.

信息

¥Message

SyntaxError: Illegal continue statement: no surrounding iteration statement (V8-based)
SyntaxError: Illegal continue statement: 'label' does not denote an iteration statement (V8-based)
SyntaxError: continue must be inside loop (Firefox)
SyntaxError: 'continue' is only valid inside a loop statement. (Safari)
SyntaxError: Cannot continue to the label 'label' as it is not targeting a loop. (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

continue 语句可用于继续循环,在其他地方使用它们是语法错误。或者,你可以向 continue 语句提供 label 以继续使用该标签的任何循环 - 但是,如果标签未引用包含语句,则会引发另一个错误 语法错误:未找到标签,并且如果标签引用不是循环的语句 ,仍然会抛出语法错误。

¥continue statements can be used to continue a loop, and using them elsewhere is a syntax error. Alternatively, you can provide a label to the continue statement to continue any loop with that label — however, if the label does not reference a containing statement, another error SyntaxError: label not found will be thrown, and if the label references a statement that is not a loop, a syntax error is still thrown.

示例

¥Examples

在回调中使用 continue

¥Using continue in callbacks

如果要在 forEach() 循环中继续进行下一次迭代,请改用 return,或将其转换为 for...of 循环。

¥If you want to proceed with the next iteration in a forEach() loop, use return instead, or convert it to a for...of loop.

js
array.forEach((value) => {
  if (value === 5) {
    continue; // SyntaxError: continue must be inside loop
  }
  // do something with value
});
js
array.forEach((value) => {
  if (value === 5) {
    return;
  }
  // do something with value
});
js
for (const value of array) {
  if (value === 5) {
    continue;
  }
  // do something with value
}

也可以看看

¥See also