a.k.a 구조분해 할당

목표


비구조화 할당에 대해 알아본다.

배열 비구조화 할당


다음 코드를 살펴보자.

let nums = ["one", "two", "three"];
let one = nums[0];
let two = nums[1];
let three = nums[2];

console.log(one, two, three);

one, two, three 변수에 값을 일일이 저장한다. 비구조화 할당을 이용하면 이럴 필요가 없다.

다음 코드를 살펴보자.

let nums = ["one", "two", "three"];
let [one, two, three] = nums;

console.log(one, two, three);

선언할 변수를 []안에 넣고 nums를 대입하였더니, 각각의 변수에 순서대로 nums가 저장이 되었다.

아예 다음과 같이 단축할 수도 있다.

let [one, two, three] = ["one", "two", "three"];

console.log(one, two, three);

출력 화면


Untitled

예외


다음처럼 받는 변수의 개수가 더 많으면 어떻게 될까?