JavaScript 中的 break 和 continue 语句有什么区别?
javascriptweb developmentfront end technology
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("退出循环!<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>