Skip to content

Array methods

JavaScript Lesson 13 2:14 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
Doubling every number in an array is something you can already do: make an empty array, write the loop yourself, push each doubled value. 把数组里每个数翻倍,这件事你已经会做了:新建一个空数组,自己写循环, 把每个翻倍后的值 push 进去。
Four lines, an index, and a counter to get right. 四行代码,一个索引,还有一个要写对的计数器。
Now here is one line instead, doing the same job. 现在换成一行,做同样的事。
It is not just shorter — there is no counter to get wrong, so a whole family of bugs simply cannot happen. 它不只是更短——里面根本没有计数器可以写错,所以一整类 bug 直接不可能发生。
Map takes a function — usually an arrow function — and runs it on every item, collecting the answers into a brand-new array. map 接收一个函数——通常是箭头函数——把它在每一项上运行一次, 并把结果收集到一个全新的数组里。
One, two, three becomes two, four, six. 1、2、3 变成 2、4、6。
Notice the shape of the change: three in, three out. 注意这个变化的形状:进去三个,出来三个。
Map never changes how many items there are; it changes what each one is. map 从不改变项的数量;它改变的是每一项是什么。
And it hands the new array back, so you must store it. 而且它会把新数组交还给你,所以你必须把它存起来。
Filter is the mirror image. filter 正好相反。
It also takes a function, but that function answers true or false, and filter keeps the ones that pass. 它同样接收一个函数,但那个函数回答的是真或假, 而 filter 保留通过判断的那些项。
Out of three, seven, two, nine and one, only two survive the greater-than-four test: seven and nine. 在 3、7、2、9、1 里,只有两项通过了“大于 4”的判断:7 和 9。
The values that stay are completely unchanged — filter changes how many, not what. 留下来的值完全没有被改变——filter 改变的是数量,不是内容。
The third one is for when you do not want a new array at all — you just want something done with each item. 第三个用在你根本不想要新数组的时候——你只是想对每一项做点什么。
forEach runs your function on every item and hands nothing back. forEach 把你的函数在每一项上运行一次,然后什么也不返回。
So if you are building a total, the total has to be declared outside and added to inside. 所以如果你在累加一个总数,这个总数必须声明在外面,在里面往上加。
Four, eight and fifteen give twenty-seven. 4、8、15 得到 27。
If you ever write const x equals something dot forEach, x will be undefined, every time. 如果你写了 const x = 某数组.forEach(...),那 x 每次都会是 undefined。
Four things to take with you. 带走四点。
One: map keeps the count and changes the values. 第一:map 保持数量不变,改变每一项的值。
Two: filter keeps the values and changes the count. 第二:filter 保持值不变,改变数量。
Three: forEach does something and returns nothing. 第三:forEach 只是做事,不返回任何东西。
Four: store what map and filter hand back, or the work is thrown away. 第四:map 和 filter 交还的结果一定要存起来,否则这些工作就白做了。
Now do the three tasks — one of each. 现在去做那三道题——每种方法各一题。

Log in or create account

IGCSE, A-Level & AP