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]