Skip to content

Arrow functions

JavaScript Lesson 11 1:57 English narration · English + 中文 subtitles burned in

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

Chapters

Transcript
Start with the function you already know how to write. 从你已经会写的那种函数开始。
First, give the function a name by storing it in a const, instead of naming it after the word function. 第一步,把它存进一个 const 来给它名字,而不是用 function 后面跟名字的写法。
Then write an arrow instead of the word function altogether. 第二步,用一个箭头彻底代替 function 这个词。
Then, when the body is a single result, drop the braces and the word return. 第三步,当函数体只是一个结果时,把花括号和 return 一起去掉。
Four lines, and every one of them does exactly the same thing — only the ceremony changes. 四行代码,每一行做的都是完全相同的事——变的只是那些形式上的东西。
One rule decides whether an arrow function gives you anything back. 有一条规则决定箭头函数会不会给你返回值。
Without braces, whatever follows the arrow is the answer, and it comes back on its own. 不加花括号时,箭头后面的东西就是答案,它会自动被返回。
With braces, you are writing an ordinary body — so if you leave the return out, nothing comes back and the call gives you undefined. 加上花括号,你写的就是一个普通的函数体—— 所以如果漏掉 return,就什么也不会返回,调用得到的是 undefined。
Braces in, you must write return. 加了花括号,就必须写 return。
That single sentence covers every arrow function you will ever write. 这一句话涵盖了你以后会写的所有箭头函数。
Now the lesson's third task: an arrow function that says whether a number is even. 现在做课程里的第三道题:写一个箭头函数,判断一个数是不是偶数。
The body is the remainder test you wrote in lesson six. 函数体就是你在第 6 课写过的取余判断。
Call it with eight and you get true, because eight is even. 传 8 进去得到 true,因为 8 是偶数。
Call it with seven and seven is not, so you get false. 传 7 进去,7 不是偶数,所以得到 false。
And notice what is missing: no if, no return true, no return false. 注意少了什么:没有 if,没有 return true,也没有 return false。
The comparison is already a boolean, so it is handed back as it stands — no if needed. 那个比较本身就是布尔值,所以它原样被返回——不需要 if。
Four things to take with you. 带走四点。
One: parameters, an arrow, then the result. 第一:形参、一个箭头,然后是结果。
Two: with no braces the value comes back on its own. 第二:没有花括号时,值会自动返回。
Three: add braces and you must write return. 第三:加了花括号,就必须写 return。
Four: an arrow function behaves exactly like the long form — this is shorthand, not a different thing. 第四:箭头函数的行为和长写法完全一样——这是简写,不是另一种东西。
Now do the three tasks; all three fit on one line each. 现在去做那三道题;三题每题都能写成一行。

Log in or create account

IGCSE, A-Level & AP