跳转到主要内容
eLearner.app
模块 4 · 第 2 课(共 4)课程中的14/32~10 min
模块课程(2/4)

箭头功能

Arrow functions are a more compact syntax for writing functions. Ideal for callbacks and short functions.

Basic syntax

JS
// classic function
const somma = function (a, b) {
  return a + b;
};

// equivalent arrow
const somma2 = (a, b) => {
  return a + b;
};

// arrow with implicit return (concise body, no braces)
const somma3 = (a, b) => a + b;

The three forms are equivalent. The third is the most "JavaScript-y".

When you can omit braces and return

If the body is a single expression:

JS
const quadrato = (n) => n * n;
const isAdult = (eta) => eta >= 18;
const saluto = (nome) => `Ciao, ${nome}!`;

If instead you need multiple statements, you need braces and an explicit return:

JS
const descrivi = (n) => {
  const parita = n % 2 === 0 ? 'pari' : 'dispari';
  return `${n} è ${parita}`;
};

One parameter: optional parentheses

JS
const triplo = (n) => n * 3;
const triplo2 = (n) => n * 3; // this is fine too

With zero or two+ parameters, parentheses are mandatory:

JS
const ora = () => Date.now();
const min = (a, b) => (a < b ? a : b);

Try it

锻炼#js.m4.l2.e1
尝试:0加载中...

Rewrite this function as an arrow function with implicit return: `function square(n) { return n * n; }`. Assign it to the const `square` and call it with 5 (expected 25).

正在加载编辑器...
显示提示

const square = (n) => n * n;

3 次尝试后可用的解决方案

Review exercise

锻炼#js.m4.l2.e2
尝试:0加载中...

Define an arrow function `describe(n)` that returns the string `<n> è pari` if n is even, otherwise `<n> è dispari`. Call it with 7 as the last expression.

正在加载编辑器...
显示提示

Use the body with braces when you have more than one expression.

3 次尝试后可用的解决方案