반응형
SMALL
스프레드 연산자(...)는 배열, 객체, 문자열 등의 요소를 개별적으로 펼쳐서 사용할 수 있도록 해주는 JavaScript 연산자.
FullCalendar 사용할 때 아래처럼 eventSources에 일정을 배열로 넣어야하는데,
eventSources: [
{
id: "대한민국 공휴일",
googleCalendarId: "ko.south_korea#holiday@group.v.calendar.google.com",
color: "#FF0000",
editable: false
},
{
id: "일정2",
color: "#FF0000",
editable: false
},
...
]
특정 eventList를 Map형태로 뽑아 전체를 넣기 위해 아래같이 사용함.
eventSources: [
eventList.map(event => ({
id: event.id,
groupId: event.id,
events: [],
backgroundColor: event.bgColor,
})), // ❌ 이렇게 하면 안됨
{
id: "대한민국 공휴일",
googleCalendarId: "ko.south_korea#holiday@group.v.calendar.google.com",
color: "#FF0000",
editable: false
}
]
문제는 eventList.map(...)이 이미 배열을 반환하기 때문에 이중배열([ [...mappedEvents], {...} ]) 형태가 되어 추가되지 않음.
이럴 때 사용하는게 스프레드 연산자!
//이렇게 사용해야 한다.
eventSources: [
...eventList.map(event => ({ // 기본 이벤트 항목 추가
id: event.id,
groupId: event.id,
events: [],
backgroundColor: event.bgColor,
})),
{
id: "대한민국 공휴일", // 대한민국 공휴일 추가
googleCalendarId: "ko.south_korea#holiday@group.v.calendar.google.com",
color: "#FF0000",
editable: false
}
],
📌 1. 배열에서의 스프레드 연산자 활용
배열을 복사하거나, 합칠 때 사용됩니다.
✅ 예제 1: 배열 복사 (얕은 복사)
const arr1 = [1, 2, 3];
const arr2 = [...arr1]; // arr1을 복사
console.log(arr2); // [1, 2, 3]
arr2 = [...arr1]를 사용하면 arr1의 개별 요소가 펼쳐져서 새로운 배열이 생성됩니다.
✅ 예제 2: 배열 합치기
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = [...arr1, ...arr2]; // 두 배열을 합침
console.log(merged); // [1, 2, 3, 4, 5, 6]
arr1과 arr2의 요소들이 개별적으로 풀려서 하나의 배열로 합쳐짐.
✅ 예제 3: 배열의 중첩 구조 해결
const arr1 = [1, 2, 3];
const arr2 = [arr1, 4, 5];
console.log(arr2);
// [[1, 2, 3], 4, 5] <-- 배열이 중첩됨
const arr3 = [...arr1, 4, 5]; // 스프레드 연산자로 펼침
console.log(arr3);
// [1, 2, 3, 4, 5] <-- 중첩되지 않고 개별 요소가 추가됨
스프레드 연산자를 사용하면 배열의 중첩 없이 개별 요소로 추가할 수 있음.
📌 2. 객체에서의 스프레드 연산자 활용
객체를 복사하거나, 속성을 병합할 때 유용합니다.
✅ 예제 4: 객체 복사
const obj1 = { name: "Alice", age: 25 };
const obj2 = { ...obj1 }; // obj1을 복사
console.log(obj2); // { name: "Alice", age: 25 }
기존 객체를 새로운 객체로 복사하는 방법.
✅ 예제 5: 객체 속성 병합
const obj1 = { name: "Alice", age: 25 };
const obj2 = { job: "Developer", city: "Seoul" };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
// { name: "Alice", age: 25, job: "Developer", city: "Seoul" }
반응형
LIST
'[ javascript ]' 카테고리의 다른 글
Node.js 뜯어보기 (0) | 2025.03.20 |
---|---|
대표적인 es6 문법 정리 (0) | 2024.12.30 |
부동소수점 이슈 (0) | 2024.03.29 |
Node.js & npm 업데이트 하기 (1) | 2024.03.22 |
리액트란? (0) | 2024.03.19 |