ES6引入了rest参数,其书写形式为:...变量名
rest 参数搭配的变量是一个数组,用于获取未赋值的剩余(不确定)参数放入数组中。
-
- 用于函数的形参上
var f=(a,...b)=>{
console.log(a); //1
console.log(b); //(2) [2, 3]
}
f(1,2,3);
可以用rest参数代替arguments变量:
//arguments
let f=function(){
console.log(arguments);
return arguments[0]+arguments[1]
}
console.log(f(1,2)); //3
// rest
let f2=(...x)=>{
console.log(x);
return x[0]+x[1];
}
console.log(f2(1,2)); //3
从以上两种写法可以看出
rest参数的写法更简洁自然。且 arguments 对象并不是数组,只是一个类数组的对象,如果要使用数组的方法,首先要使用 Array.from 将其转为数组,而rest参数返回就是一个数组,可以直接使用数组的方法,以 sort 排序为例:
function s() {
return Array.from(arguments).sort();
}
//
const s2 = (...x) => x.sort();
console.log(s(1,2,5,4,3));
console.log(s2(1,2,5,4,3));
//(5) [1, 2, 3, 4, 5]
rest参数必须作为最后一个形式参数存在,即之后不能再有其他参数:
function f(a,...b,c){
//console.log(a); //1
//console.log(b); //[2,3]
}
f(1,2,3);
rest 参数不计入函数的length属性:
function f(a,...b){
console.log(a); //1
console.log(b); //[2,3]
}
f(1,2,3);
console.log( f.length); //1
-
- 与解构赋值组合
const [a,...b]=[1,2,3];
console.log(a); //1
console.log(b); //[2,3]
同 set 数据集合一起使用,实现数组去重:
const arr=[1,2,3,4,2,5,1];
const [...newArr]=new Set(arr);
console.log(newArr); //(5) [1, 2, 3, 4, 5]