Development/Javascript
[Javascript/ES6+] Destructuring(구조분해문법)
레오나르도 다빈츠
2021. 7. 7. 21:06
출처
자바스크립트 ES6+ 기본 - 인프런 | 강의
4개 강좌로 구성된 자바스크립트 바이블 강좌의 3번째 강좌입니다. 자바스크립트 스펙의 95% 이상을 다룹니다. ES6+ 환경에서 새로운 패러다임의 프로그램을 개발할 수 있습니다., 자바스크립트
www.inflearn.com
🚀 Destructuring
◽ Destructuring
- Destructuring Assignment(분할 할당)
- 원 데이터는 변경되지 않는다.
[코드 1: Destructuring]
let one, two, three;
const list = [1, 2, 3];
[one, two, three] = list;
console.log(one);
console.log(two);
console.log(three);
console.log(list);
[실행결과]
1
2
3
[1, 2, 3]
◽ Array 분할 할당
1) 배열의 엘리먼트를 분할하여 할당
[코드 1: 인덱스 기준으로 할당]
let one, two, three;
[one, two, three] = [1, 2, 3];
console.log(one);
console.log(two);
console.log(three);
[실행결과]
1
2
3
[코드 2: 할당받을 변수 수가 적은 경우]
let one, two;
[one, two] = [1, 2, 3];
console.log(one);
console.log(two);
console.log(three);
[실행결과]
1
2
[코드 3: 할당받을 변수 수가 많은 경우]
let one, two, three, four;
[one, two, three, four] = [1, 2, 3];
console.log(three);
console.log(four);
[실행결과]
2
undefined
[코드 4: 배열 차원에 맞추어 분할 할당]
let one, two, three, four;
[one, two, [three, four]] = [1, 2, [3, 4]];
// 2차원 배열이지만 차원을 무시하고 1차원으로 펼쳐준다.
console.log(one two, [three, four]);
[실행결과]
2
undefined
[코드 5: 배열 차원에 맞추어 분할 할당]
let one, two, three, four;
[one, two, [three, four]] = [1, 2, [3, 4]];
// 2차원 배열이지만 차원을 무시하고 1차원으로 펼쳐준다.
console.log([one, two, [three, four]]);
[실행결과]
2
undefined
[코드 6: 인덱스에 변수가 없을 때]
let one, two, three, four;
[one, , , four] = [1, 2, 3, 4];
// 인덱스를 건너 뛰어 할당한다.
console.log(one, two, three, four);
[실행결과]
1, undefined, undefined, 4
2) Spread와 같이 사용하는 경우
[코드 1: 나머지를 전부 할당]
let one, rest;
[one, ...rest] = [1, 2, 3, 4];
console.log(one);
console.log(rest);
[실행결과]
1
[2, 3, 4]
[코드 2: 인덱스를 반영한 나머지를 할당]
let one, three, rest;
[one, , three, ...rest] = [1, 2, 3, 4, 5];
console.log(three);
console.log(rest);
[실행결과]
3
[4, 5]
📌 추가로 참고하면 좋은 글!
Destructuring | Vue.js + ES6
구조 분해 문법(Destructuring) 디스트럭처링이라고 하는 이 ES6 문법은 한글로 번역하면 구조 분해 문법입니다. 구조 분해(?)라는 억지스러운 용어를 설명하기 전에 여기서 말하는 '구조'라는 단어를
joshua1988.github.io