[Tech] 구조 분해 할당 & spread/rest 문법
[Tech] 구조 분해 할당 & spread/rest 문법
구조 분해 할당이란?!
- ES6부터 객체 or 배열의 값을 추출해서 바로 할당할 수 있는 편리한 문법이 도입되었다.
- 미리 분할해서 값을 명시하는 방법으로, 비구조화 할당이라고도 부른다.
- 배열 구조 분해 할당
1 2 3 4 5
const [a, b, c] = [25, 26, 27]; console.log(a); // 25 console.log(b); // 26 console.log(c); // 27
- 객체 구조 분해 할당
1 2 3 4 5 6 7 8 9
const { name, age, address } = { name: "jaegeon"; age: 26; address: "GyeongKi-Do"; } console.log(name); // jaegeon console.log(age); // 26 console.log(address); // GyeongKi-Do
Spread와 Rest는 무엇인가?!
- 여기서, Spread와 Rest가 의미하는 바가 뭔지 살펴보면,
- Spread는 객체 or 배열 데이터를 여러 개의 요소로 펼치는 것을 의미한다.
- Rest는 반대로 여러 개의 요소를 하나의 배열로 만는 것을 의미한다.
따라서, 이 둘을 가능케 하는 연산자가 바로
...!
- Spread 예시
1 2 3
const arr = [23, 24, 25, 26]; console.log(...arr); // 23 24 25 26
- Rest 예시
1 2 3 4 5
function func(...rest) { console.log(rest); } func(23, 24, 25, 26); // [23, 24, 25, 26]
✨ 출처
This post is licensed under CC BY 4.0 by the author.