while loops · while 循环
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
while repeats
while (test) { ... }runs again and again, as long as the test staystrue.- It checks the test before each pass — so the body might run zero times.
中文
while 重复
while (test) { ... }一遍又一遍地运行,只要测试一直为true。- 它在每一轮之前检查测试 —— 所以循环体有可能一次都不运行。
let n = 1;
while (n <= 3) {
console.log(n); // → 1, then 2, then 3
n++;
}
English
Make progress every pass
- Something inside must move the test toward
false. - If nothing changes, the loop never stops — an infinite loop (the Stop button saves you).
中文
每一轮都要有进展
- 里面必须有东西把测试推向
false。 - 如果什么都不变,循环永远不停 —— 这就是死循环(Stop 按钮能救你)。
let n = 1;
while (n < 50) {
n = n * 2; // 2, 4, 8, 16, 32, 64 — then stop
}
console.log(n); // → 64
Explore · 探索
Each pass doubles n · 每一轮 n 翻倍
while re-checks its test each pass. n must change, or it runs forever. · while 每一轮都重新检查测试。n 必须改变,否则会永远运行。
English
Common mistakes
- Change the condition inside the loop, or it runs forever.
- A
whilechecks its condition first, so it may run zero times.
中文
常见错误
- 在循环里改动条件,否则会无限运行。
while先检查条件,所以可能一次都不运行。
English
Now you try
- Use a
whileloop. - Press Check answer to test it.
中文
现在轮到你
- 使用
while循环。 - 按检查答案来测试它。
let n = 3. Use a while loop to count down · 下: log 3, 2, 1, one per line. · let n = 3。用 while 循环倒数:打印 3、2、1,每行一个。
Click Run to see the output here. · 点击“运行”查看此处输出。
let n = 1. While n is 16 or less, log n then double it. Output should be 1, 2, 4, 8, 16. · let n = 1。当 n 在 16 及以下时,打印 n 再把它翻倍。输出应为 1、2、4、8、16。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use a while loop to add up 1 to · 到 4, then log the total (it is 10). · 用 while 循环把 1 到 4 加起来,然后打印总和(是 10)。
Click Run to see the output here. · 点击“运行”查看此处输出。