JavaScript 中 break 語句和 continue 語句的區別是什麼?
break 語句
break 語句用於提前退出迴圈,跳出包含它的花括號。break 語句會退出迴圈。
讓我們來看一個 JavaScript 中 break 語句的例子。下面的例子演示了 break 語句與 while 迴圈的用法。注意,一旦 x 達到 5,迴圈就會提前退出,並執行緊跟在閉合花括號後面的 document.write(..) 語句。
示例
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5) {
break; // breaks out of loop completely
}
x = x +1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>continue 語句
continue 語句告訴直譯器立即開始迴圈的下一個迭代,並跳過剩餘的程式碼塊。當遇到 continue 語句時,程式流程會立即移動到迴圈檢查表示式,如果條件仍然為真,則開始下一個迭代;否則,控制權將退出迴圈。
continue 語句會跳過迴圈中的一個迭代。此示例演示了 continue 語句與 while 迴圈的用法。注意如何使用 continue 語句來跳過變數 x 中的索引達到 8 時的列印操作。
示例
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10) {
x = x+ 1;
if (x == 8){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP