Skip to content

Putting it together

JavaScript Lesson 15 2:04 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
One more loop before the end, and it is the one you will reach for most. 结束之前再看一种循环,而它会是你以后最常用的那一个。
The version you know needs a counter and an index — three things to write, and an off-by-one waiting in each of them. 你已经会的那种写法需要一个计数器和一个索引——要写三样东西, 而每一样里都埋着一个差一错误。
The for of loop drops all of that: n is the value itself, one item per pass. for…of 把这些全去掉了:n 就是那个值本身,每轮一项。
Use for of whenever you want every item and do not care where it sits. 当你想遍历每一项、又不关心它在第几位时,就用 for…of。
Now look at the three tasks waiting for you, because they are the same shape. 现在看看等着你的那三道题,因为它们是同一个形状。
Something before the loop, a loop over the array, an update inside, a return after. 循环之前放一样东西,循环遍历数组,里面更新它,循环之后返回它。
Only two slots differ. 只有两个位置不同。
For a sum, a total starts at zero and each pass adds. 求和时,total 从 0 开始,每轮相加。
For the largest, it starts at the first item and each pass keeps the bigger. 求最大值时,它从第一项开始,每轮保留较大的那个。
For a count, the counter starts at zero and only passes that beat the limit add one. 计数时,计数器从 0 开始,只有超过界限的那些轮次才加 1。
One skeleton, three fillings. 一套骨架,三种填法。
Here is the last one written out. 这是最后一题的完整写法。
Count starts at zero. count 从 0 开始。
The loop visits every number. 循环访问每一个数字。
The if tests it against the limit, and count plus plus runs only when the test passes. if 把它和界限比较,只有通过判断时才执行 count++。
With four, eight and fifteen against a limit of five, eight and fifteen pass, so the answer is two. 对 4、8、15,界限是 5,8 和 15 通过,所以答案是 2。
Raise the limit to twenty and nothing passes, so it returns zero — which is the right answer, not a failure. 把界限提高到 20,没有一个通过,于是返回 0—— 这是正确答案,不是出错。
Four things, and then you are done with this course. 四点,然后这门课就结束了。
One: for of gives you the value, not the index. 第一:for…of 给你的是值,不是索引。
Two: start, loop, update, return — one skeleton behind most array work. 第二:初始化、循环、更新、返回——大多数数组操作背后都是这一套骨架。
Three: one function, one job, then combine them. 第三:一个函数只做一件事,然后把它们组合起来。
Four: build a piece, test it, and only then add the next. 第四:写一小块,测一小块,然后再加下一块。
As for where to go next: the web-basics course puts this JavaScript into a real page, with buttons that do something. 至于接下来去哪里:web-basics 课程会把这些 JavaScript 放进一个真正的页面里, 让按钮真的做点什么。
Well done. 做得好。

Log in or create account

IGCSE, A-Level & AP