1. 程式人生 > >es6可變引數-擴充套件運算子

es6可變引數-擴充套件運算子

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);//6

es6中可變引數:

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

...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]