... 문법은 사용 위치에 따라 spread 또는 rest로 동작한다.
spread
spread 연산자는 배열이나 객체를 펼쳐서 개별 요소로 분리한다.
사용 시점
- 객체나 배열을 복사하거나 합칠 때
- 함수 호출 시 배열의 요소를 개별 인수로 전달할 때
객체 복사 및 확장
const toy = {
type: "bear",
price: 15000,
};
const blueToy = {
...toy,
color: "blue",
};
const yellowToy = {
...toy,
color: "yellow",
};
console.log(blueToy); // { type: 'bear', price: 15000, color: 'blue' }
console.log(yellowToy); // { type: 'bear', price: 15000, color: 'yellow' }
배열 합치기
const color1 = ["red", "orange", "yellow"];
const color2 = ["blue", "navy", "purple"];
const rainbow = [...color1, 'green', ...color2];
console.log(rainbow); // [ 'red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple' ]
함수 인수로 전달
const print = (a, b, c, d, e, f) => {
console.log(a, b, c, d, e, f);
};
const numbers = [1, 2, 3, 4, 5, 6];
print(...numbers); // 1 2 3 4 5 6
rest
rest 연산자는 나머지 요소들을 하나로 묶어서 배열이나 객체로 만든다.
사용 시점
- 구조 분해 할당에서 나머지 요소를 묶을 때
- 함수 매개변수에서 가변 인자를 받을 때
구조 분해 할당에서 나머지 묶기
const blueToy = {
type: "bear",
price: 15000,
color: "blue",
};
// 구조분해할당을 통해 프로퍼티의 값을 변수들에 할당
const {type, price, color} = blueToy;
console.log(type); // bear
console.log(price); // 15000
console.log(color); //blue
주의할 점
rest는 항상 마지막 위치에 작성해야 한다. 중간이나 앞에 위치하면 오류가 발생한다.
// TypeError const {...rest, type} = blueToy; // ❌
배열에서 나머지 요소 묶기
const color = ["red", "orange", "yellow", "green"];
const [c1, c2, ...rest] = color;
console.log(c1, c2); // red orange
console.log(rest); // [ 'yellow', 'green' ]
함수 매개변수로 가변 인자 받기
const print = (a, b, ...rest) => {
console.log(a, b, rest);
};
print(1, 2, 3, 4, 5, 6); // 1 2 [ 3, 4, 5, 6 ]
spread와 rest 함께 사용
const print = (...rest) => {
console.log(rest);
};
const numbers = [1, 2, 3, 4, 5, 6];
print(...numbers); // [ 1, 2, 3, 4, 5, 6 ]'TIL' 카테고리의 다른 글
| [TS] 타입 단언 (0) | 2025.10.31 |
|---|---|
| 웹페이지를 조작하는 DOM (0) | 2025.10.31 |
| 구조 분해 할당 (0) | 2025.10.31 |
| [TS] 타입 추론 및 타입 정의 연습 (0) | 2025.10.31 |
| [TS] 타입 추론 (0) | 2025.10.31 |
