Skip to content

for loops

JavaScript Lesson 8 2:33 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
A JavaScript for loop packs three separate jobs into one set of brackets, separated by two semicolons. JavaScript 的 for 循环把三件不同的事塞进同一对圆括号里,中间用两个分号隔开。
The first part sets the counter up, and it runs once, before anything else. 第一部分设置计数器,它只在最开始执行一次。
The second part is the test, and it is checked before every pass — while it is true, the loop keeps going. 第二部分是判断,每一轮之前都会检查——只要为真,循环就继续。
The third part is the step, and it runs after each pass. 第三部分是步进,它在每一轮之后执行。
Start, test, step: name them and the line stops looking like punctuation soup. 起始、判断、步进:给它们各起个名字,这一行就不再像一堆标点了。
Watch what the counter does. 看看计数器做了什么。
It starts at one, and takes each value in turn: one, two, three, four, five. 它从 1 开始,依次取到每一个值:1、2、3、4、5。
For every one of those the body runs once, so the console gets five lines. 每取到一个值,循环体就执行一次,所以控制台得到五行。
Then the counter becomes six, the test asks whether six is at most five, the answer is false, and the loop stops at five without running the body again. 然后计数器变成 6,判断问 6 是不是小于等于 5,答案为假, 循环就在 5 这里停下,不会再执行一次循环体。
The last value it uses is the last one that passes the test. 它用到的最后一个值,就是最后一个通过判断的值。
The commonest thing you will do inside a loop is build up a total, and there is one rule that decides whether it works. Declare the total before the loop. 在循环里面你最常做的事就是累加出一个总数,而有一条规则决定它能不能成立: 要在循环之前声明这个总数。
Put let total inside the braces and a brand-new total is made on every pass, set back to zero, and thrown away at the end of it. 如果把 let total 写在花括号里面,那么每一轮都会新建一个 total, 重新设为 0,并在这一轮结束时被丢掉。
Declared outside, it survives, and it grows each pass: one, three, six, all the way to fifty-five. 写在外面,它就能存活下来,并且每一轮都在增长:1、3、6,一直到 55。
Now the lesson's third task: log the even numbers two, four and six. 现在做课程里的第三道题:打印偶数 2、4、6。
Nothing new is needed — just different numbers in the same three slots. 不需要任何新东西——只是在同样的三个位置换成不同的数字。
Start at two instead of one. 起始从 2 开始,而不是 1。
Keep the test as at most six. 判断仍然是小于等于 6。
And for the step, write i plus-equals two, which adds two instead of one. 步进写成 i += 2,也就是每次加 2 而不是加 1。
That is the whole point of the three-part header: change the parts, and it counts anything you like. 这正是三段式头部的意义:换掉其中的部分,它就能按你想要的方式计数。
Four things to take with you. 带走四点。
One: the header holds start, test and step, separated by semicolons. 第一:头部里放的是起始、判断和步进,用分号隔开。
Two: the test is checked before every pass, so a loop can run zero times. 第二:判断在每一轮之前检查,所以循环可能一次都不执行。
Three: i plus plus adds one, and i plus-equals two steps by two. 第三:i++ 每次加 1,i += 2 每次加 2。
Four: a total must be declared outside the loop, or it never grows. 第四:总数必须在循环外面声明,否则它永远不会增长。
Now do the three tasks; the middle one builds a total. 现在去做那三道题;中间那题要累加一个总数。

Log in or create account

IGCSE, A-Level & AP