最後迴圈值
重要性:3
這段程式碼發出警示的最後一個值是什麼?為什麼?
let i = 3;
while (i) {
alert( i-- );
}
答案:1
。
let i = 3;
while (i) {
alert( i-- );
}
每次迴圈反覆都會讓 i
遞減 1
。檢查 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