function add(...others){
console.log(others); // [1, 2, 3, 4, 5]
let total = 0;
for(let i = 0; i < others.length; i++){
total += others[i];
}
return total;
}
let result = add(1, 2, 3, 4, 5);
console.log(result); // 15
範例 2:
延續上例,測試看看這個:
/* Rest Operator:用在函式 */
function add(a, b, ...others){
console.log(a); // 1
console.log(b); // 2
console.log(others); // [3, 4, 5]
let total = 0;
for(let i = 0; i < others.length; i++){
total += others[i];
}
return total;
}
let result = add(1, 2, 3, 4, 5);
console.log(result); // 12