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]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM