描述 JavaScript Break、Continue 和 Label 语句
javascriptweb developmentfront end technology更新于 2024/4/18 6:34:00
break 语句
break 语句用于提前退出循环,跳出封闭的花括号。break 语句退出循环。
让我们看一个 JavaScript 中 break 语句的示例。以下示例说明了如何在 while 循环中使用 break 语句。请注意,一旦 x 达到 5,循环就会提前跳出,并到达紧挨着结束花括号下方的 document.write (..) 语句
示例
<html> <body> <script> var x = 1; document.write("进入循环<br /> "); while (x < 20) { if (x == 5) { break; // 完全跳出循环 } x = x + 1; document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); </script> </body> </html>
continue 语句
continue 语句告诉解释器立即开始循环的下一次迭代并跳过剩余的代码块。遇到 continue 语句时,程序流立即移动到循环检查表达式,如果条件保持为真,则开始下一次迭代,否则,控制退出循环。
continue 语句中断循环中的一次迭代。此示例说明了如何在 while 循环中使用 continue 语句。请注意如何使用 continue 语句在变量 x 中保存的索引达到 8 时跳过打印
示例
<html> <body> <script> var x = 1; document.write("进入循环<br /> "); while (x < 10) { x = x + 1; if (x == 8) { continue; // 跳过循环体的其余部分 } document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); </script> </body> </html>
标签语句
JavaScript 标签语句用于将标签添加到标识符的前缀。标签可以与 break 和 continue 语句一起使用,以更精确地控制流程。标签只是一个标识符,后跟一个冒号 (:),应用于语句或代码块。我们将看到两个不同的例子来了解如何将标签与 break 和 continue 一起使用。
您可以尝试运行以下代码,使用标签控制流程,使用 break 语句
示例
<html> <body> <script> document.write("Entering the loop!<br /> "); outerloop: // 这是标签名称 for (var i = 0; i < 5; i++) { document.write("Outerloop: " + i + "<br />"); innerloop: for (var j = 0; j < 5; j++) { if (j > 3 ) break ; // 退出最内层循环 if (i == 2) break innerloop; // 执行相同操作 if (i == 4) break outerloop; // 退出外层循环 document.write("Innerloop: " + j + " <br />"); } } document.write("Exiting the loop!<br /> "); </script> </body> </html>