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

迴圈至少執行一次。

do {
  // loop body
} while (condition);

let i = 0;
do {
  alert( i );
  i++;
} while (i < 3);

The “for” loop

for (begin; condition; step) {
  // ... loop body ...
}

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

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

for (let i = 0; i < 3; i++) {
  alert(i); // 0, 1, 2
}
alert(i); // error, no such variable

// global variable
let i = 0;

for (i = 0; i < 3; i++) { // use an existing variable
  alert(i); // 0, 1, 2
}

alert(i); // 3, visible, because declared outside of the loop

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

let i = 0; // we have i already declared and assigned

for (; i < 3; i++) { // no need for "begin"
  alert( i ); // 0, 1, 2
}

let i = 0;

for (; i < 3;) {
  alert( i++ );
}

Breaking the loop

break 可以離開迴圈。

let sum = 0;

while (true) {
  let value = +prompt("Enter a number", '');
  if (!value) break; // (*)
  sum += value;
}

alert( 'Sum: ' + sum );

Continue to the next iteration

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

for (let i = 0; i < 10; i++) {
  // if true, skip the remaining part of the body
  if (i % 2 == 0) continue;
  alert(i); // 1, then 3, 5, 7, 9
}

// same, side-effect less readability
for (let i = 0; i < 10; i++) {
  if (i % 2) {
    alert( i ); // if there are multi lines to execute
  }
}

在 ? operator 不能使用 break / continue

if (i > 5) { // worked
  alert(i);
} else {
  continue;
}

// same
(i > 5) ? alert(i) : continue; // continue isn't allowed here

Labels for break/continue

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

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    let input = prompt(`Value at coords (${i},${j})`, '');
    // if an empty string or canceled, then break out of both loops
    if (!input) break outer; // (*)
    // do something with the value...
  }
}

alert('Done!');

Last updated