レッスンに戻る

ループの最後の値

重要度: 3

このコードによって警告される最後の値はなんですか?なぜですか?

let i = 3;

while (i) {
  alert( i-- );
}

回答: 1.

let i = 3;

while (i) {
  alert( i-- );
}

ループが反復されるごとにi1ずつ減らされます。チェックwhile(i)i = 0のときにループを停止します。

したがって、ループのステップは次のシーケンスを形成します(「ループの展開」)

let i = 3;

alert(i--); // shows 3, decreases i to 2

alert(i--) // shows 2, decreases i to 1

alert(i--) // shows 1, decreases i to 0

// done, while(i) check stops the loop