ES6 rest参数和扩展运算符

rest参数

ES6引入了rest参数(形式为“…变量名”)。其中rest参数搭配的变量是一个数组可以使用数组的一切操作。

例:

function rest(...values){
    let sum=0;
    for(var val of values){
        sum+=val;
    }
    return sum;
}
add(1,2,3)//6

值得注意的是rest参数之后不能再有其他参数(只能是最后一个参数)否则会报错。

例:

function rest(a,...b,c){
}//报错

函数的length属性不包括rest参数。

(function(...a){}).length  //0

扩展运算符

例:

console.log(1,...[2,3,4],5) //1 2 3 4 5 

可以替代apply方法:

Math.max.apply(null,[14,3,7])   //ES5写法
Math.max(...[14,3,7]) //ES6写法

用于合并数组:

[1,2].concat(more) //ES5
[1,2, ...more] //ES6

与解构赋值结合:

let [first,...rest]=[1,2,3,4,5];
first //1
rest  //[2,3,4,5]

如果将扩展运算符用于数组复制,只能放在参数最后一位,否则会报错

[...rest,last]=[1,2,3,4,5]
//报错
原文地址:https://www.cnblogs.com/miangao/p/7308253.html