rest運算符也是三個點號,不過其功能與擴展運算符恰好相反,把逗號隔開的值序列組合成一個數(shù)組。
//主要用于不定參數(shù),所以ES6開始可以不再使用arguments對象
var bar = function(...args) {
for (let el of args) {
console.log(el);
}
}
bar(1, 2, 3, 4);
//1
//2
//3
//4
bar = function(a, ...args) {
console.log(a);
console.log(args);
}
bar(1, 2, 3, 4);
//1
//[ 2, 3, 4 ]
rest運算符配合解構(gòu)使用:
var [a, ...rest] = [1, 2, 3, 4];
console.log(a);//1
console.log(rest);//[2, 3, 4]