0x000 概述
剩餘參數將沒有對應形參的參數聚合成一個數組
0x001 語法
function(a, b, ...theArgs) {
}
0x002 只聚合未對應形參參數
剩餘參數只會將沒有對應形參的參數聚合成一個數組, 而arguments
則是包含了所有的參數。
function add(a, b, ...theArgs) {
return {rest: theArgs, arguments}
}
add()
// {rest: [undefined, undefined, []], arguments: Arguments(0)}
add(1)
// {rest: [1, undefined, []], arguments: Arguments(1)}
add(1, 2)
// {rest: [1, 2, []], arguments: Arguments(2)}
add(1, 2, 3, 4, 5)
// {rest: [1, 2, [3, 4, 5]], arguments: Arguments(5)}
0x003 剩餘參數是數組
剩餘參數始終是一個數組,而不像arguments
是一個僞數組
function add(...theArgs) {
console.log(Array.isArray(theArgs))
theArgs.forEach((a)=>console.log(a))
console.log(Array.isArray(arguments))
Array.prototype.slice.call(arguments, add.length).forEach((a)=>console.log(a)) // 轉化成數組
}
add(1,2,3) // true 1 2 3 false 1, 2, 3, 4
0x004 解構剩餘參數
function add(...[a, b, c]){
return a + b +c
}
add(1, 2, 3) // 6
add(1, 2, 3) // 6
0x005 使用babel
翻譯
function add(...num){
return num.reduce((n1,n2)=>n1+n2)
}
翻譯後
function add() {
for (var _len = arguments.length, num = Array(_len), _key = 0; _key < _len; _key++) {
num[_key] = arguments[_key];
}
return num.reduce(function (n1, n2) {
return n1 + n2;
});
}