使用while迴圈,只要某個條件成立,就能重複執行程式碼。
它的寫法是在while關鍵字後面接著包在括號中的條件,以及一個以大括號包住、內含迴圈_主體_的程式區塊。
while (condition) {
// code that is executed repeatedly as long as the condition is
// true
}
JavaScript 也有 do-while 迴圈。 這種迴圈會先執行迴圈主體,然後才檢查條件。 當條件取決於主體中所做的評估時,這就很有用。
do {
// The code here will always be executed once and then
// repeatedly while the condition is true.
} while (condition);
在迴圈主體中,你可以使用break關鍵字來完全停止迴圈的執行。
這經常搭配true作為條件使用。
這樣一來,你就能從迴圈主體中的任何位置控制迴圈何時應該停止。
const winningNumber = 7;
while (true) {
const num = readUserGuess();
if (num === winningNumber) {
break;
}
}
break關鍵字不能用於巢狀在迴圈中的函式內,範例請見 MDN 文件。
與break不同,continue關鍵字只會停止目前這次疊代的執行,並繼續進行下一次疊代。
使用continue時,你通常可以避免將迴圈主體的大部分內容包在if敘述中。
let i = 0;
while (i < 100) {
i = i + 2;
if (i % 3 === 0) {
continue;
}
// The code here will only be executed when i was not divisible
// by 3 in the check above.
}
當迴圈條件永遠成立,而且在迴圈主體中不會遇到 break 或 return 敘述時,就會產生一個(理論上)永遠重複的迴圈。 這種執行必須從外部終止。 視這類程式碼執行的環境而定,終止可能是自動發生,也可能需要手動介入。
let i = 0;
while (i < 100) {
if (i % 3 === 0) {
continue;
}
i = i + 2;
}
// This loop runs forever since the variable i does not change
// anymore after it is divisible by 3 the first time.
在這個簡單的範例中,看出無限迴圈可能看似簡單,但面對更複雜的程式碼時,就不總是那麼容易了。 良好的做法是徹底思考你的條件最終是否會變成 false,或者你的 break 或 return 敘述是否會被執行到。