Loops: while and for

The “while” loop

無限迴圈,當判斷式為真,迴圈會持續執行,直到判斷式為錯誤。

while (condition) {
  // code
  // so-called "loop body"
}

let i = 0;
while (i < 3) { // shows 0, then 1, then 2
  alert( i );
  i++;
}

// single line omit {...}
let i = 3;
while (i) alert(i--);

The “do…while” loop

迴圈至少執行一次。

The “for” loop

變數被宣告在迴圈裡面,只能在迴圈內使用,除非使用變數為全域變數。

for 迴圈可以忽略任何部分,但;要存在不然會有 syntax error。

Breaking the loop

break 可以離開迴圈。

Continue to the next iteration

continue 可以停止當次運算,開始下次運算。

在 ? operator 不能使用 break / continue

Labels for break/continue

label 停止巢狀迴圈,用 break 只能停止一個迴圈。

Last updated

Was this helpful?