continue语句用于跳过当前循环迭代的剩余代码并进入下一次循环,只能在for、while或do...while循环内部使用,不可单独出现在if、函数或switch中。

在 JavaScript 中,continue 语句用于跳过当前循环迭代的剩余代码,直接进入下一次循环。它常用于过滤掉无效、空值、不符合条件的数据,让循环只处理“有效”的项。
continue 只能在循环中使用
continue 必须写在 for、while 或 do...while 循环内部,否则会报错 Illegal continue statement。它不能用在 if 单独块里,也不能用在函数或 switch 中(除非该 switch 在循环内)。
- ✅ 正确:在
for循环中判断后continue - ❌ 错误:在普通
if外层直接写continue
在 for 循环中跳过空值或非数字项
比如遍历一个混合数组,只想处理数字类型:
const data = [1, '', null, 42, undefined, 'hello', 7];
for (let i = 0; i
<h3>在 for...of 中配合 if 使用 continue</h3>
<p><code>for...of</code> 同样支持 <code>continue</code>,写法更简洁直观:</p>
<pre class="brush:php;toolbar:false;">const items = ['a', 0, 'b', false, 'c', NaN];
for (const item of items) {
if (!item) continue; // 跳过 falsy 值(0、false、''、null、undefined、NaN)
console.log('有效项:', item);
}
// 输出:有效项: a,有效项: b,有效项: c
注意:!item 会把 0 和 false 当作无效,如果业务需要保留 0,应改用更精确的判断,例如 item === undefined || item === null || item === ''。
避免 continue 和 break 混淆
continue 是“跳过本次”,break 是“彻底退出”。容易误用的场景:
- 想跳过某个对象但继续处理下一个?→ 用
continue - 发现错误要立刻停止整个循环?→ 用
break - 嵌套循环中想跳过外层某次迭代?→ 需配合标签(label),例如
outer: for (...) { ... continue outer; }
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











