Arrow functions · 箭头函数
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Arrow functions
- A shorter way to write a function:
const square = (n) => n * n;. - With a single expression after
=>, the value is returned automatically — noreturn, no{ }.
中文
箭头函数
- 一种更简短的函数写法:
const square = (n) => n * n;。 - 当
=>后面只有一个表达式时,它会自动返回 —— 不用return,也不用{ }。
const square = (n) => n * n;
console.log(square(5)); // → 25
English
More than one parameter
- List the parameters in the brackets, separated by commas.
中文
多于一个参数
- 把参数列在括号里,用逗号隔开。
const add = (a, b) => a + b;
console.log(add(3, 4)); // → 7
English
Watch out
- Need a longer body? Use
{ }and then you must writereturnyourself. - Arrow functions shine as short helpers — you will hand them to
.mapand.filterwhen we reach array methods.
中文
注意
- 需要更长的函数体?用
{ },这时你就必须自己写return。 - 箭头函数最适合做简短的小助手 —— 到讲数组方法时你会把它交给
.map和.filter。
English
Common mistakes
x => x + 1is a short function; with no braces it returns the expression.- Arrow functions are handy as arguments to array methods.
中文
常见错误
x => x + 1是简短函数;不加大括号时会自动返回表达式。- 箭头函数很适合当数组方法的参数。
English
Now you try
- Write each arrow function.
- Press Check answer to test it.
中文
现在轮到你
- 写出每个箭头函数。
- 按检查答案来测试它。
Write an arrow function triple that returns its argument times 3: const triple = (n) => n * 3;. · 写一个箭头函数 triple,返回它的参数乘以 3:const triple = (n) => n * 3;。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write an arrow function add with two parameters that returns their sum. · 写一个有两个参数的箭头函数 add,返回它们的和。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write an arrow function isEven that returns true when its argument is even (n % 2 === 0). · 写一个箭头函数 isEven,当参数为偶数(n % 2 === 0)时返回 true。
Click Run to see the output here. · 点击“运行”查看此处输出。