JavaScript Break 和 Continue
JavaScript break 和 continue
Section titled “JavaScript break 和 continue”break 和 continue 语句是控制流语句,它们改变了循环 (for、while、do...while) 和 switch 语句的执行流程。
break 语句完全终止当前的循环或 switch 语句。
continue 语句跳过当前循环的当前迭代(iteration),并继续进行下一次迭代。
break 语句
Section titled “break 语句”你可能已经在 switch 语句中遇到过 break,用于防止穿透(fall-through)。它也常用于当满足特定条件时提前退出循环。
当 break 在循环内部执行时,循环会立即终止,程序执行将继续循环后面的语句。
示例:查找元素并停止。
let numbers = [10, 20, 30, 40, 50];let foundAt = -1;let target = 30;let output = "";
for (let i = 0; i < numbers.length; i++) { output += `Checking ${numbers[i]}\n`; if (numbers[i] === target) { foundAt = i; output += `Found ${target} at index ${i}. Breaking loop.\n`; break; // Exit the loop once the target is found }}output += `Loop finished. Target found at index: ${foundAt}`;// console.log(output) would show that checking stops after 30.如果没有 break,即使找到目标后,循环仍会继续检查所有数字。
continue 语句
Section titled “continue 语句”continue 语句用于循环内部,跳过当前迭代的剩余部分,并继续进行下一次迭代。
示例:只处理偶数。
let result = "";for (let i = 0; i < 10; i++) { if (i % 2 !== 0) { // If the number is odd continue; // Skip the rest of this iteration } result += `Processing even number: ${i}\n`;}// console.log(result) would show only even numbers processed.在这个例子中,如果 i 是奇数,continue 会被执行,并且该迭代中 result += ... 的代码行会被跳过。然后循环会继续进行 i 的下一个值。
常见的学习障碍:break 与 continue
记住:break 退出整个循环。continue 只退出当前迭代。
JavaScript 标签
Section titled “JavaScript 标签”JavaScript 允许你为语句加上标签。标签是一个标识符,后跟冒号(:),放置在语句或代码块之前。
labelName: statementOrBlockbreak 和 continue 可以与标签一起使用,以控制嵌套循环或特定代码块的执行流程。这是一个不太常用的特性,但在某些场景下可能很有用。
带标签的语法:
break labelName;continue labelName;使用 break 与标签:
Section titled “使用 break 与标签:”一个 break labelName; 语句将终止与 labelName 相关联的代码块或循环的执行。
示例:跳出嵌套循环。
let outputText = "";outerLoop: // Label for the outer loopfor (let i = 0; i < 3; i++) { outputText += `Outer loop (i=${i}):\n`; for (let j = 0; j < 3; j++) { outputText += ` Inner loop (j=${j})\n`; if (i === 1 && j === 1) { outputText += ` Breaking out of outerLoop!\n`; break outerLoop; // Exits both inner and outer loops } }}outputText += "After loops.";// console.log(outputText) would show loops stopped after i=1, j=1.使用 continue 与标签:
Section titled “使用 continue 与标签:”一个 continue labelName; 语句将跳过被标记循环的当前迭代,并继续进行 该特定被标记循环 的下一次迭代。
示例:从内层循环继续外层循环。
let log = "";outer:for (let i = 0; i < 3; i++) { log += `Outer i=${i}\n`; for (let j = 0; j < 3; j++) { if (j === 1) { log += ` Inner j=${j}, continuing outer\n`; continue outer; // Skips rest of inner, goes to next iteration of outer } log += ` Inner j=${j}\n`; }}// console.log(log) would show inner loop only processes j=0 for each i.关于标签的注意事项:
虽然标签提供了强大的控制能力,但有时会使代码更难阅读和调试。请谨慎使用。通常,将代码重构为更小的函数是比复杂的带标签的 break 或 continue 语句更易读的选择。
代码块是一系列用花括号 {} 包围的语句。 |
|---|
注意:break 和 continue 适用于传统的 for、for...of、for...in、while 和 do...while 循环。它们不能直接中断(break)或继续(continue)数组方法,如 forEach()。对于 forEach(),你可以从回调函数中 return 来达到类似 continue 跳过当前项的效果,但你无法 break forEach() 循环本身(你需要使用 Array.prototype.some() 或 Array.prototype.every(),或者改用传统循环)。