Skip to content

Arrays

JavaScript Lesson 12 2:22 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
An array holds several values in order, under one name, written in square brackets. 数组把若干个有顺序的值放在一个名字下面,写在方括号里。
Each item sits at a numbered position, counting from zero — the same numbering you met in the strings lesson, for the same reason. 每一项都待在一个编号的位置上,从 0 开始数—— 和你在字符串那一课见到的编号方式一样,原因也一样。
So to reach the second item you ask for position one, not position two. 所以要取第二项,你要写位置 1,而不是位置 2。
That is the one thing to get used to, and everything else about arrays follows from it. 需要习惯的就是这一点,数组的其他一切都由它推出来。
An array is not a fixed size. 数组的大小不是固定的。
Dot push adds one item to the end, while the program is running — which is how you collect results, readings or answers without knowing in advance how many there will be. .push() 会在程序运行的过程中往末尾添加一项—— 你就是这样在事先不知道数量的情况下,把结果、读数或答案收集起来的。
And dot length tells you how many there are right now: two before the push, three after it. .length 告诉你此刻有多少项:push 之前是 2,之后是 3。
Length is a property, so it takes no brackets. length 是一个属性,所以后面不加括号。
To visit every item you use a for loop, and its header is worth reading slowly. 要访问每一项就用 for 循环,而它的头部值得慢慢读。
The counter starts at zero, because that is where the array starts. 计数器从 0 开始,因为数组就是从 0 开始的。
It runs while i is LESS than length — not less than or equal. 循环条件是 i 小于 length——不是小于等于。
With four items the length is four, but the last index is three, so less-than-or-equal would reach past the end and hand you undefined. 四项的时候 length 是 4,但最后一个索引是 3, 所以写成小于等于就会越过末尾,取到 undefined。
Start at zero, stop before the length: that is the whole shape. 从 0 开始,在 length 之前停下:整个结构就是这样。
Now the lesson's fourth task: add up every number in an array. 现在做课程里的第四道题:把数组里的每个数加起来。
Two things before the loop — the array itself, and a total that starts at zero, declared outside so it survives. 循环之前有两样东西——数组本身,以及一个从 0 开始的 total, 它声明在循环外面,所以能存活下来。
Then each pass adds one item, reached by its index. 然后每一轮按索引取出一项加上去。
Watch the total climb: four, twelve, twenty-seven, and finally forty-three. 看着总数往上走: 4、12、27,最后是 43。
Three lines that work for four numbers or four hundred. 三行代码,四个数能用,四百个数也能用。
Four things to take with you. 带走四点。
One: square brackets hold many values in order. 第一:方括号按顺序装下多个值。
Two: the first item is index zero, so the second is index one. 第二:第一项是索引 0,所以第二项是索引 1。
Three: push adds to the end, and length counts them. 第三:push 往末尾添加,length 数出有多少项。
Four: loop while i is less than length — never less than or equal. 第四:循环条件写 i 小于 length——绝不要写小于等于。
Now do the four tasks; the last one is the summing loop. 现在去做那四道题;最后一题就是那个求和循环。

Log in or create account

IGCSE, A-Level & AP