Skip to content

while loops

JavaScript Lesson 9 2:26 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
A for loop is right when the number of passes is written down in the loop itself — one to five is five passes, and you can see it. 当循环次数就写在循环本身里的时候,for 循环最合适——1 到 5 就是五轮,一眼可见。
But now suppose you start at one and keep doubling until you go past sixteen. 但现在假设你从 1 开始,不断翻倍,直到超过 16。
How many passes is that? 那是多少轮?
You would have to work it out, and there is nothing to write in a for header. 你得自己算一算,而 for 的头部里没有东西可写。
So JavaScript gives you a loop that repeats on a condition instead. 所以 JavaScript 给了你另一种循环:它按条件重复。
The machine is simple. 这台机器很简单。
The loop asks first: is the condition true? 循环先问:条件为真吗?
If it is, it runs the block. 如果为真,就执行那个代码块。
Then it comes back and asks again — that returning arrow is the whole loop. 然后它回来再问一次——那条返回的箭头就是整个循环。
When the answer finally comes back false, it carries on past the loop to whatever follows. 当答案终于变成假时,它就越过循环,继续执行后面的内容。
And because the question comes first, a while loop can run zero times, which a for loop can too, for the same reason. 因为问题问在前面,while 循环可能一次都不执行——for 循环也是如此,道理相同。
That returning arrow is also where it goes wrong. 那条返回的箭头也正是出错的地方。
In the first version nothing changes n, so the condition is true forever and the program never stops — the console fills with threes until you press Stop. 第一个版本里没有任何东西改变 n, 所以条件永远为真,程序永远停不下来——控制台会一直打印 3,直到你按下停止。
One more line fixes it: n minus minus takes one away each pass. 加一行就解决了:n-- 每一轮减去 1。
Now the value walks down to zero and the test eventually fails. 这样这个值就一步步走到 0,判断最终会失败。
Every while loop needs a line like that, and it is the first thing to look for when one hangs. 每个 while 循环都需要这样一行,而当循环卡住时,这也是第一个该检查的地方。
Now the lesson's second task, the doubling one. 现在做课程里的第二道题,就是翻倍那一题。
Start n at one. 让 n 从 1 开始。
While n is at most sixteen, log it, then double it — so n doubles each pass: one, two, four, eight, sixteen. 只要 n 小于等于 16,就打印它,然后把它翻倍——所以 n 每轮翻一倍: 1、2、4、8、16。
After sixteen it becomes thirty-two, the test fails, and the loop ends. 16 之后它变成 32,判断失败,循环结束。
Five passes, and notice the number five appears nowhere in that code. 一共五轮,而请注意,代码里根本没有出现数字 5。
That is exactly when a while is the right tool. 这正是该用 while 的时候。
Four things to take with you. 带走四点。
One: a while repeats on a condition, not a count. 第一:while 按条件重复,而不是按次数。
Two: the test comes first, so the body may run zero times. 第二:判断在前,所以循环体可能一次都不执行。
Three: change something every pass, or it never ends. 第三:每一轮都要改变某个东西,否则它永远不会结束。
Four: if one runs away from you, press Stop — it is not a disaster, it is a missing line. 第四:万一循环失控了,就按停止——那不是灾难,只是少了一行。
Now do the three tasks; the first is a countdown. 现在去做那三道题;第一题是倒计时。

Log in or create account

IGCSE, A-Level & AP