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>
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP