其余参数

剩余参数语法允许函数接受不定数量的参数作为数组,提供了一种在 JavaScript 中表示 可变参数函数 的方法。

¥The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

Try it

语法

¥Syntax

js
function f(a, b, ...theArgs) {
  // …
}

描述

¥Description

函数定义的最后一个参数可以以 ...(三个 U+002E 句号字符)为前缀,这将导致所有剩余的(用户提供的)参数被放置在 Array 对象中。

¥A function definition's last parameter can be prefixed with ... (three U+002E FULL STOP characters), which will cause all remaining (user supplied) parameters to be placed within an Array object.

js
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]

一个函数定义只能有一个剩余参数,并且剩余参数必须是函数定义中的最后一个参数。

¥A function definition can only have one rest parameter, and the rest parameter must be the last parameter in the function definition.

js
function wrong1(...one, ...wrong) {}
function wrong2(...wrong, arg2, arg3) {}

其余参数不计入函数的 length 属性。

¥The rest parameter is not counted towards the function's length property.

剩余参数和 arguments 对象之间的区别

¥The difference between rest parameters and the arguments object

其余参数与 arguments 对象之间存在三个主要区别:

¥There are three main differences between rest parameters and the arguments object:

  • arguments 对象不是真正的数组,而其余参数是 Array 实例,这意味着可以直接对其应用 sort()map()forEach()pop() 等方法。
  • arguments 对象具有额外的(已弃用的)callee 属性。
  • 在具有简单参数的非严格函数中,arguments 对象 将其索引与参数值同步。重新分配命名参数时,剩余参数数组永远不会更新其值。
  • 其余参数将所有额外参数打包到一个数组中,但不包含在 ...restParam 之前定义的任何命名参数。arguments 对象包含所有参数(包括 ...restParam 数组中的参数),并打包到一个类似数组的对象中。

示例

¥Examples

使用剩余参数

¥Using rest parameters

在此示例中,第一个参数映射到 a,第二个参数映射到 b,因此这些命名参数可以正常使用。

¥In this example, the first argument is mapped to a and the second to b, so these named arguments are used as normal.

然而,第三个参数 manyMoreArgs 将是一个数组,其中包含第三个、第四个、第五个、第六个、…、第 n 个 - 用户指定的参数数量。

¥However, the third argument, manyMoreArgs, will be an array that contains the third, fourth, fifth, sixth, …, nth — as many arguments as the user specifies.

js
function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// a, "one"
// b, "two"
// manyMoreArgs, ["three", "four", "five", "six"] <-- an array

下面,即使只有一个值,最后一个参数仍然被放入一个数组中。

¥Below, even though there is just one value, the last argument still gets put into an array.

js
// Using the same function definition from example above

myFun("one", "two", "three");

// a, "one"
// b, "two"
// manyMoreArgs, ["three"] <-- an array with just one value

下面,没有提供第三个参数,但 manyMoreArgs 仍然是一个数组(尽管是一个空数组)。

¥Below, the third argument isn't provided, but manyMoreArgs is still an array (albeit an empty one).

js
// Using the same function definition from example above

myFun("one", "two");

// a, "one"
// b, "two"
// manyMoreArgs, [] <-- still an array

下面,只提供了一个参数,因此 b 获得默认值 undefined,但 manyMoreArgs 仍然是一个空数组。

¥Below, only one argument is provided, so b gets the default value undefined, but manyMoreArgs is still an empty array.

js
// Using the same function definition from example above

myFun("one");

// a, "one"
// b, undefined
// manyMoreArgs, [] <-- still an array

参数长度

¥Argument length

由于 theArgs 是一个数组,因此其元素的计数由 length 属性给出。如果函数的唯一参数是剩余参数,则 restParams.length 将等于 arguments.length

¥Since theArgs is an array, a count of its elements is given by the length property. If the function's only parameter is a rest parameter, restParams.length will be equal to arguments.length.

js
function fun1(...theArgs) {
  console.log(theArgs.length);
}

fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3

将剩余参数与普通参数结合使用

¥Using rest parameters in combination with ordinary parameters

在下一个示例中,使用剩余参数将第一个参数之后的所有参数收集到数组中。然后将收集到数组中的每个参数值乘以第一个参数,然后返回数组:

¥In the next example, a rest parameter is used to collect all parameters after the first parameter into an array. Each one of the parameter values collected into the array is then multiplied by the first parameter, and the array is returned:

js
function multiply(multiplier, ...theArgs) {
  return theArgs.map((element) => multiplier * element);
}

const arr = multiply(2, 15, 25, 42);
console.log(arr); // [30, 50, 84]

从参数到数组

¥From arguments to an array

Array 方法可用于剩余参数,但不能用于 arguments 对象:

¥Array methods can be used on rest parameters, but not on the arguments object:

js
function sortRestArgs(...theArgs) {
  const sortedArgs = theArgs.sort();
  return sortedArgs;
}

console.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7

function sortArguments() {
  const sortedArgs = arguments.sort();
  return sortedArgs; // this will never happen
}

console.log(sortArguments(5, 3, 7, 1));
// throws a TypeError (arguments.sort is not a function)

引入剩余参数是为了减少通常用于将一组参数转换为数组的样板代码。

¥Rest parameters were introduced to reduce the boilerplate code that was commonly used for converting a set of arguments to an array.

在剩余参数之前,需要先将 arguments 转换为普通数组,然后再对其调用数组方法:

¥Before rest parameters, arguments need to be converted to a normal array before calling array methods on them:

js
function fn(a, b) {
  const normalArray = Array.prototype.slice.call(arguments);
  // — or —
  const normalArray2 = [].slice.call(arguments);
  // — or —
  const normalArrayFrom = Array.from(arguments);

  const first = normalArray.shift(); // OK, gives the first argument
  const firstBad = arguments.shift(); // ERROR (arguments is not a normal array)
}

现在,你可以使用剩余参数轻松访问普通数组:

¥Now, you can easily gain access to a normal array using a rest parameter:

js
function fn(...args) {
  const normalArray = args;
  const first = normalArray.shift(); // OK, gives the first argument
}

规范

Specification
ECMAScript Language Specification
# sec-function-definitions

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看