Javascript 简明教程

JavaScript - Arrow Functions

Arrow Functions

JavaScript 中的 arrow functions 允许我们创建更短的 anonymous 函数。箭头函数被编写为不带 "function" 关键字。JavaScript 箭头函数是在 ES6 中引入的。

The arrow functions in JavaScript allow us to create a shorter and anonymous function. Arrow functions are written without "function" keyword. The JavaScript arrow functions are introduced in ES6.

在 ES6 之前,我们可以使用函数声明或函数表达式定义 JavaScript 函数。函数表达式用于定义匿名函数。箭头函数允许我们使用更短的语法编写函数表达式。

Before ES6, we can define a JavaScript function with function declaration or function expression. The function expressions are used to define anonymous functions. The arrow functions allow us to write the function expressions with shorter syntax.

让我们看看下面的语法来编写函数表达式 −

Let’s look at the below syntax to write a function expression −

const varName = function(parameters) {
    // function body
};

上面的函数表达式可以被写成箭头函数 −

The above function expression can be written as an arrow function −

const varName = (parameters) => {
    // function body
};

这里移除了 "function" 关键字,并且在括号后面添加了 "⇒"。

Here the "function" keyword is removed and after parenthesis we added "⇒".

Syntax

在 JavaScript 中使用箭头函数的语法如下。

The syntax to use the arrow function in JavaScript is as follows.

const varName = (p1, p2, ... pN) => Expression;
OR
const varName = (p1, p2, ...pN) => {
    // function body
};

这里参数 p1、p2、…、pN 是可选的。我们可以使用变量名称后跟一对括号来调用箭头函数。

Here the parameters p1, p2, …, pN are optional. We can use the variable name followed by pair of parentheses to invoke the arrow function.

Arrow Function with Single Statement

当箭头函数包含一个语句时,我们不需要编写 'return' 关键字和大括号。

When the arrow function contains a single statement, we don’t need to write the 'return' keyword and braces (curly brackets).

const add = (x, y) => x +y;

请注意,我们总是可以使用 return 关键字和大括号来编写一个箭头函数。

Please note, we can always write an arrow function with return keyword and braces.

const add = (x, y) => {return x + y};

Example

在下面的示例中,箭头函数仅包含一个语句,因此我们不需要使用大括号或 return 语句。

In the example below, the arrow function contains a single statement, so we don’t need to use the curly braces or return statement.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const divide = (x, y) => x / y;
      document.getElementById("output").innerHTML = divide(10, 5);
   </script>
</body>
</html>
2

Arrow Function with Multiple Statements

当函数体包含多条语句时,我们应该始终使用 'return' 语句来返回一个值。此外,我们应该使用大括号。

When the function body contains multiple statements, we should always use the 'return' statement to return a value. Also we should use the curly brackets.

Example

在下面的示例中,箭头函数包含多条语句,因此我们需要使用大括号或 return 语句。

In the example below, the arrow function contains multiple statements, so we need to use the braces or return statement.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const divide = (x, y) => {
         let res = x / y;
         return res;
      };
      document.getElementById("output").innerHTML = divide(10, 5);
   </script>
</body>
</html>
2

请注意,当我们使用大括号作为代码块时,我们必须使用 return 语句。

Note when we use block body using braces, we must use return statement.

Arrow Functions Without Parameters

上述语法中的参数 p1、p2、……、pN 是可选的。我们可以编写没有参数的箭头函数。

The parameters p1, p2, …, pN, in the above syntaxes are options. We can write an arrow function without any parameters.

const greet = () => "Hello World!";

我们还可以使用大括号和 return 关键字编写代码块:

We can also write using block body using braces and return keyword −

const greet = () => {return "Hello World!";};

Example

<html>
<body>
   <p id = "output"> </p>
   <script>
      const greet = () => "Hello World!";
      document.getElementById("output").innerHTML = greet();
   </script>
</body>
</html>
Hello World!

Arrow Function with Parameters

Example: Arrow function with a single parameter

以下代码演示了当需要将一个参数传递给函数时,不需要在圆括号中编写参数。

The below code demonstrates that when you need to pass a single parameter to the function, you don’t need to write parameters in the pair of parenthesis.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const divide = x => 20 / x;
      let res = divide(2);
      document.getElementById("output").innerHTML =
      "The value returned from the arrow function is: " + res;
   </script>
</body>
</html>
The value returned from the arrow function is: 10

Example: Arrow function with multiple parameters

我们在下面的代码中将多个参数传递给箭头函数表达式。当箭头函数的主体包含多条语句时,我们需要将其写在花括号内并使用 return 语句来返回该值。

We pass the multiple parameters to the arrow function expression in the code below. When the body of the arrow function contains multiple statements, we need to write it inside the curly braces and use the return statement to return the value.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const sum = (a, b, c, d) => {
         let sum = a + b + c + d;
            return sum;
      };
      let res = sum(10, 30, 45, 60);
      document.getElementById("output").innerHTML =
      "The sum of 10, 30, 45, and 60 is: " + res;
   </script>
</body>
</html>
The sum of 10, 30, 45, and 60 is: 145

Arrow Function as an Expression

由于箭头函数的语法较短,因此它可以很容易地用作一个表达式。

The arrow function can easily be used as an expression due to its shorter syntax.

Example

在下面的代码中,我们使用了三元运算符,并根据 'isMul' 变量的布尔值将箭头函数表达式分配给 'func' 变量。

In the below code, we use the ternary operator, and based on the boolean value of the 'isMul' variable, we assign the arrow function expression to the 'func' variable.

之后,我们使用 'func' 变量来调用存储在其中的箭头函数。

After that, we use the 'func' variable to call the arrow function stored in that.

<html>
<body>
   <p id="output"> </p>
   <script>
      let isMul = true;
      const func = isMul ? () => {
         let res = 5 * 5;
         document.getElementById("output").innerHTML +=
		 "The multiplication value is: " + res + "<br>";
      } : () => {
         let res = 5 + 5;
         document.getElementById("output").innerHTML +=
         "The sum value is: " + res + "<br>";
      };

      func();
   </script>
</body>
</html>
The multiplication value is: 25

Arrow Function with Default Parameters

Example

下面的代码解释了程序员如何将默认参数传递给箭头函数。它类似于我们将默认参数传递给标准函数定义的方式。

The below code explains how programmers can pass the default parameters to the arrow function. It is similar as we pass default parameters to the standard function definition.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const output = document.getElementById("output");
      let isMul = true;
      const mul = (a = 10, b = 15) => a * b;
      output.innerHTML += "mul(5, 8) = " + mul(5, 8) + "<br>";
      output.innerHTML += "mul(6) = " + mul(6) + "<br>";
      output.innerHTML += "mul() = " + mul() + "<br>";
   </script>
</body>
</html>
mul(5, 8) = 40
mul(6) = 90
mul() = 150

Benefits of Using Arrow Functions

在此,我们解释了使用箭头函数的好处。

Here, we have explained the benefits of using the arrow functions.

  1. Shorter syntax − The arrow function decreases the code size to define the function.

  2. Implicit return − To return the resultant value of the expression from the arrow function containing only a single statement, developers don’t need to use the return keyword.

  3. Ease to use as expression − The arrow function can be easily used as an expression.

Limitations of Using Arrow Function

箭头函数有一些局限性,我们将在下面解释一下。

There are some limitations of arrow functions, which we have explained below.

  1. No Arguments − The arrow function can’t have an arguments object.

  2. No prototype − The arrow function can’t have a prototype property as it is stored in the variable as an expression.

  3. No new keyword − The arrow function can’t be used with the new keyword to create its object.