나머지 매개변수 구문을 사용하면 함수가 정해지지 않은 수의 매개변수를 배열로 받을 수 있습니다.
function sum(...theArgs) {
let total = 0;
for (const arg of theArgs) {
total += arg;
}
return total;
}
console.log(sum(1, 2, 3));
// Expected output: 6
console.log(sum(1, 2, 3, 4));
// Expected output: 10
함수의 마지막 매개변수 앞에 "..."(세 개의 U+002E FULL STOP 문자)를 붙이면 (사용자가 제공한) 모든 후속 매개변수를 표준 JavaScript 배열에 넣도록 지정합니다. 마지막 매개변수만 나머지 매개변수로 설정할 수 있습니다.
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// 콘솔 출력:
// a, one
// b, two
// manyMoreArgs, [three, four, five, six]
참조
foo(...one, ...wrong, ...wrong);
함수 정의에는 하나의 ...만 존재할 수 있습니다.
나머지 매개변수와 arguments 객체 사이에는 세 개의 주요 차이가 있습니다.