Spread 연산자는 배열이나 객체를 개별 요소로 분리하는 데 사용됩니다. 이를 통해 배열이나 객체의 요소를 쉽게 복사하거나 합칠 수 있습니다.
const arr1 = [1, 2, 3];
const newArr1 = [...arr1];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
const arr3 = [4, 5];
const arr4 = [...arr1, ...arr3]; // [1, 2, 3, 4, 5]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
const obj3 = { b: 4, d: 5 };
const obj4 = { ...obj1, ...obj3 }; // { a: 1, b: 4, d: 5 }
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
함수의 인자나 배열 또는 객체에서 나머지 요소를 하나의 변수로 수집하는 데 사용됩니다. Rest 연산자는 주로 함수의 매개변수에서 사용되며, 남은 모든 인자를 배열로 모을 수 있습니다.
function sum(...args) {
return args.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest); // [2, 3, 4]
cf) const [...rest, last] 이런건 불가능
const { a, ...rest } = { a: 1, b: 2, c: 3 };
console.log(a); // 1
console.log(rest); // { b: 2, c: 3 }