循环 (for & 虽然)
学习如何循环 repeat code automatically — for 循环 for counted repeats and 虽然循环 for conditional ones.
你将学到
- 为什么循环 exist and 什么它们 replace
- 如何 for 循环数量通过范围
- 如何虽然循环 repeats 直到条件失败
- 如何 avoid 无限循环
概念讲解
Loops (for & while)
Loops repeat a block of code multiple times. Without loops, you would have to copy and paste the same lines for every repetition — imagine printing "Hello" 100 times by hand. Loops let you write the instruction once and say "do this N times."
The for Loop
A for loop is used when you know how many times to repeat. It has three parts: initialization, condition, and update.
for (let i = 0; i < 5; i++) {
console.log("Iteration", i);
}
// Prints: Iteration 0, 1, 2, 3, 4
let i = 0— runs once, before the loop starts.i < 5— checked before each iteration; the loop continues while true.i++— runs after each iteration, incrementing the counter.
The while Loop
A 虽然 loop is used when you do not know how many repetitions you need — you repeat until a condition becomes false.
let dice = 0;
while (dice !== 6) {
dice = Math.floor(Math.random() * 6) + 1;
console.log("Rolled:", dice);
}
Beware Infinite Loops
An infinite loop never stops because its condition never becomes false. This freezes the program. Always make sure the loop's progress eventually breaks the condition — for example, that i increases toward the limit, or that dice can actually reach 6.
Use break to exit a loop early and continue to skip to the next iteration when you need finer control.
示例代码
// for loop: count down from 5
for (let i = 5; i > 0; i--) {
console.log(i);
}
console.log("Liftoff!");
// while loop: double a number until it exceeds 100
let value = 1;
let steps = 0;
while (value <= 100) {
value *= 2;
steps++;
}
console.log(`Reached ${value} in ${steps} steps`); // Reached 128 in 7 steps
for 循环数量下 因为 i-- decreases i 每个步骤. 虽然循环 keeps doubling 直到条件 (值 <= 100) 是假.
动手试一试
- Crontab Generator
Cron 表达式是 essentially 循环 in 时间 — '运行每个 N minutes'. See 如何 repeating schedules 工作.
常见错误
错误写法
编写虽然循环谁的条件能 从不 become 假.
正确做法
Ensure 循环请求体更改变量 used in 条件. Mentally trace: 做 progress happen 每个 iteration?
错误写法
Off-通过-one 错误: using < 相反的 <=.
正确做法
Decide whether 端点是 inclusive. for (let i = 0; i <= n; i++) 运行 n+1 次数; i < n 运行 n 次数. 测试边界.
相关资源
相关代码片段
- JavaScript 数组方法
数组方法如 forEach and 映射是 循环 in disguise.
练习 循环 (for & 虽然)
12 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。