ES6 引入 rest 参数(形式为...变量名
),用于获取函数的多余参数,这样就不需要使用arguments
对象了。rest
参数搭配的变量是一个数组,该变量将多余的参数放入数组中。
function add(...values) {
var sum = 0;
for (var value of values) {
sum += value;
}
return sum;
}
add(2, 5, 3) // 10
下面是一个 rest
参数代替arguments
变量的例子。
// arguments变量的写法
function fun1() {
return Array.prototype.slice.call(arguments).sort();
}
// rest参数的写法
var fun2 = (...nums) => nums.sort();
arguments
对象不是数组,而是一个类似数组的对象。所以为了使用数组的方法,必须使用Array.prototype.slice.call
先将其转为数组。rest
参数就不存在这个问题,它就是一个真正的数组,数组特有的方法都可以使用。
注意,rest
参数之后不能再有其他参数(即只能是最后一个参数),否则会报错。
// 报错
function f(a, ...b, c) {
// ...
}
函数的length
属性,不包括 rest
参数。
(function(a) {}).length // 1
(function(...a) {}).length // 0
(function(a, ...b) {}).length // 1