es6可变参数-扩展运算符

时间:2021-02-02 20:22:04

es5中参数不确定个数的情况下:

//求参数和
function f(){
var a = Array.prototype.slice.call(arguments);
var sum = 0;
a.forEach(function(item){
sum += item*1;
})
return sum;
};
f(1,2,3);//

es6中可变参数:

function f(...a){
let sum = 0;
a.forEach(item =>{
sum += item*1;
})
return sum;
}
f(1,2,3);//

...a 为扩展运算符,这个 a 表示的就是可变参数的列表,为一个数组

合并数组

//es5
var param = ['hello',true,7];
var other = [1,2].concat(param);
console.log(other);//[1, 2, "hello", true, 7]
//es6
var param = ['hello',true,7];
var other = [1,2,...param];
console.log(other);// [1, 2, "hello", true, 7]