程式設計的核心價值之一,就是將重複性工作交給機器。JavaScript 提供了多種循環機制,while 是最基礎、最靈活的循環結構,理解它是掌握所有循環的基石。
while (condition) {
// 當 condition 為 true 時重複執行
// 必須在內部修改條件相關變量,否則陷入無限循環
}
conditiontrue,執行循環體false,跳出循環,繼續執行後續代碼<script>
var count = 0;
document.write("Starting Loop<br />");
while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++; // 關鍵:修改條件變量,避免死循環
}
document.write("Loop stopped!");
</script>
輸出結果:
Starting Loop
Current Count : 0
Current Count : 1
...
Current Count : 9
Loop stopped!
// ❌ 錯誤:忘記更新計數器
var i = 0;
while (i < 5) {
console.log(i);
// 缺少 i++,條件永遠為 true
}
// ✅ 正確
var i = 0;
while (i < 5) {
console.log(i);
i++;
}
do {
// 循環體(至少執行一次)
} while (condition); // 注意結尾分號
do...while 會無條件先執行一次循環體,然後再判斷條件決定是否繼續。這在「至少需要執行一次」的場景極其有用,如:
<script>
var count = 0;
document.write("Starting Loop<br />");
do {
document.write("Current Count : " + count + "<br />");
count++;
} while (count < 0); // 條件初始即為 false
document.write("Loop stopped!");
</script>
輸出結果:
Starting Loop
Current Count : 0
Loop stopped!
雖然 count < 0 為假,但循環體仍執行了一次。
| 特性 | while | do...while |
|---|---|---|
| 判斷時機 | 循環前 | 循環後 |
| 最少執行次數 | 0 次 | 1 次 |
| 適用場景 | 未知次數、可能零次的循環 | 必須先執行一次的交互場景 |
| 語法結尾 | 無特殊要求 | 必須以分號結尾 |
寫循環前先明確:
// ❌ 差:每次迭代都查詢 DOM
while (i < items.length) {
document.getElementById('container').innerHTML += items[i];
i++;
}
// ✅ 好:緩存 DOM、批量操作
var container = document.getElementById('container');
var html = '';
while (i < items.length) {
html += items[i];
i++;
}
container.innerHTML = html;
當循環次數固定或基於計數器時,for 循環語義更清晰,將初始化、條件、遞增集中在一行,減少變量汙染。
while 與 do...while 是 JavaScript 循環的基石。前者「審慎派」,後者「行動派」。掌握它們的異同與適用場景,並養成「明確終止條件、及時更新變量」的習慣,是寫出健壯循環代碼的關鍵。