Javascript 简明教程

JavaScript - Rest Parameter

Rest Parameter

JavaScript 中的 rest parameter 使函数可以接受一个可变数量的参数作为数组。当需要传递给函数的参数数量不固定时,可以使用剩余参数。

The rest parameter in JavaScript allows a function to accept a variable number of arguments as an array. When the number of arguments that need to pass to the function is not fixed, you can use the rest parameters.

JavaScript 剩余参数允许你在单个数组中收集所有剩余的参数。剩余参数用三个点(…​)加上一个参数名表示。此参数名是包含所有剩余参数的数组。

The JavaScript rest parameters allow you to collect all the remaining arguments in a single array. The rest parameter is represented with three dots (…​) followed by a parameter name. This parameter name is the array that contains all the remaining arguments.

Rest Parameter Syntax

JavaScript 中的剩余参数涉及在函数声明中使用三个点(…​)加上一个参数名。

The rest parameter in JavaScript involves using three dots (…​) followed by a parameter name in the function declaration.

function functionName(para1, para2, ...theArgs){
   // function body;
}

其中,para1 和 para2 是普通参数,而 theArgs 是剩余参数。剩余参数会收集剩余的参数(此处为不对应于参数(para1 和 para1)的其他参数),并将其分配给名为 theArgs 的数组。

Here para1, and para2 are ordinary parameters while theArgs is a rest parameter. The rest parameter collects the rest of arguments (here, arguments other than the corresponding to the parameters – para1 and para1) and assigns to an array named theArgs.

我们还可以像函数声明中一样在函数表达式中编写剩余参数。

We can write the rest parameter in function expression also same as in the function declaration.

rest parameter 应该始终是函数定义中的最后一个参数。

The rest parameter should always be the last parameter in the function definition.

function funcName(...para1, para2, para2){}
// SyntaxError: Invalid or unexpected token

函数定义只能有一个剩余参数。

The function definition can have only one rest parameter.

function funcName(para1, ...para2, ...para3){}
//SyntaxError: Rest parameter must be last formal parameter

Example: Variable Length Parameter List

当你想要定义一个可以处理可变数量的参数的函数时,剩余参数非常有用。让我们看以下示例:

The rest parameters are very useful when you want to define a function that can handle a variable number of arguments. Let’s take the following example −

<html>
<body>
  <div> Rest parameter allows function to accept nay number of arguments.</div>
  <div id = "demo"> </div>
  <script>
    function sum(...nums) {
      let totalSum = 0;
      for (let num of nums) {
        totalSum += num;
      }
      return totalSum;
    }
    document.getElementById("demo").innerHTML =
	 sum(10, 20, 30, 40) + "<br>" +
    sum(10, 20) + "<br>" +
    sum();
  </script>
</body>
</html>
Rest parameter allows function to accept nay number of arguments.
100
30
0

在此处,剩余参数 nums 允许函数接受任意数量的数字参数。

Here, the rest parameter nums allows the function to accept any number of number arguments.

Example: Finding the Maximum Number

JavaScript 剩余参数简化了在给定数字集中查找最大数字的过程。

JavaScript rest parameter simplifies the process of finding the max number among a set of given numbers.

在这个示例中,我们使用 rest 参数 numbers 来收集传递给函数的所有参数。展开运算符用来将各个值传给 Math.max() 函数。

In this example, we use rest parameter to numbers to collect all arguments passed to the function. The spread operator is used to pass the individual values to the Math.max() function.

<html>
<body>
   <div> Finding the maximum number</div>
   <div id = "demo"> </div>
   <script>
      function getMax(...args){
         return Math.max(...args);
      }
      document.getElementById("demo").innerHTML =
		getMax(10,20,30,40) + "<br>" +
      getMax(10,20,30);
  </script>
</body>
</html>
Finding the maximum number
40
30

这里的 rest 参数 args 允许函数 getMax 接受任意数量的参数。

Here the rest parameter args allows the function getMax to accept any number of arguments.

Spread Operator and Rest Parameters

展开运算符(…​)与 rest 参数密切相关,并且常常与它们一起使用。虽然 rest 参数将函数参数收集到一个数组中,但展开运算符执行相反的操作,将数组的元素展开到独立的参数中。

The spread operator (…​) is closely related to rest parameters and is often used in conjunction with them. While the rest parameter collects function arguments into an array, the spread operator performs the opposite operation, spreading the elements of an array into individual arguments.

在上述找到最大值的示例中,我们同时使用了 rest 参数和展开运算符。

In the above example of finding the maximum number, we used both rest parameter and spread operator.

function getMax(...args){ // here ...args as rest parameter
    return Math.max(...args); // here ... works as spread operator
}

Example

在这个示例中,展开运算符 …​ 被用来将 numbers 数组作为一个独立的参数传递给 multiply 函数的元素。

In this example, the spread operator …​ is used to pass the elements of the numbers array as individual arguments to the multiply function.

<html>
<body>
   <div> Spread operator in JavaScript<div>
   <div id="demo"></div>
   <script>
      function multiply(a, b, c) {
         return a * b * c;
      }
      const numbers = [2, 3, 4];
      document.getElementById("demo").innerHTML = multiply(...numbers);
   </script>
</body>
</html>
Spread operator in JavaScript
24

Rest Parameter vs. Arguments Object

rest 参数的引入对我们如何处理可变长度参数列表的方式产生了影响,与使用 arguments 对象相比。我们来比较两种方法:

The introduction of rest parameters has implications for how we handle variable-length parameter lists compared to using the arguments object. Let’s compare the two approaches:

Rest Parameters

<html>
<body>
  <div> Sum using rest parameter in JavaScript:</div>
  <div id = "demo"> </div>
  <script>
    function sum(...numbers) {
      return numbers.reduce((total, num) => total + num, 0);
    }
    document.getElementById("demo").innerHTML = sum(1, 2, 3, 4, 5);
  </script>
</body>
</html>
Sum using rest parameter in JavaScript:
15

Arguments Object

<html>
<body>
  <div> Sum using arguments object in JavaScript:</div>
  <div id = "demo"> </div>
  <script>
    function sum() {
      const argsArray = Array.from(arguments);
      return argsArray.reduce((total, num) => total + num, 0);
    }
    document.getElementById("demo").innerHTML = sum(1, 2, 3, 4, 5);
  </script>
</body>
</html>
Sum using arguments object in JavaScript:
15

两种方法得到的结果相同,但 rest 参数的语法更加简洁易读。它还与其他现代 JavaScript 特征更保持一致性。

While both approaches achieve the same result, the rest parameter syntax is more concise and readable. It also behaves more consistently with other modern JavaScript features.

Destructuring with Rest Parameter

解构赋值是在 ES6 中引入的。它让我们访问数组的独立值,无需使用数组索引。我们可以使用解构赋值来从由 rest 参数创建的数组中提取值。

The destructuring assignment is introduced in ES6. It allows us to access the individual values of the array without using array indexing. We can use the destructuring assignment to extract the values from the array created by rest parameter.

Example

在下面的示例中,解构赋值从 numbers 数组中提取了前两个元素。

In the example below, the destructuring assignment extracts the first two elements from the numbers array.

<html>
<body>
  <div> Destructuring assignment with rest parameter</div>
  <div id = "demo"> </div>
  <script>
    function getFirstTwo(...numbers) {
      const [first, second] = numbers;
      return `First: ${first}, Second: ${second}`;
    }
    document.getElementById("demo").innerHTML = getFirstTwo(1, 2, 3, 4, 5);
  </script>
</body>
</html>
Destructuring assignment with rest parameter
First: 1, Second: 2