Destructuring Assignment
작성 형태
let one, two, three;
const list = [1, 2, 3];
[one, two, three] = list;
console.log(one); //1
console.log(two); //2
console.log(three); //3
console.log(list);// //[1,2,3]
사전적 의미로는 구조를 파괴한다는 의미가 있는데, 코드를 보면 원 데이터가 파괴된다기보다는 구조분해후 특정요소 pick을 한다는게 더 맞는 의미입니다. 즉, 파괴보다는 분할/분리에 더 가깝다고 볼 수 있고, "분할 할당"이라고 할 수 있습니다.
인덱스에 해당하는 변수에 할당
⇒ 왼쪽의 인덱스에 해당하는 오른쪽 배열의 값을 할당합니다. one에 1, two에 2, three에 3이 할당됩니다.
let one, two, three;
[one, two, three] = [1, 2, 3];
console.log(one);
console.log(two);
console.log(three);
⇒ 왼쪽에 할당받을 변수가 분할 할당할 값보다 적은 경우 왼쪽 인덱스에 맞추어 값을 할당합니다. 그렇기에 3은 할당되지 않습니다.
let one, two;
[one, two] = [1, 2, 3];
console.log(one);
console.log(two);
⇒ 왼쪽의 할당받을 변수가 3개이고 분할 할당할 값이 2개라면 왼쪽에 값을 할당할 수 없는 변수에는 undefined가 설정됩니다.
let one, two, three;
[one, two, three] = [1, 2];
console.log(two);//2
console.log(three);//undefined
⇒[three, four]와 [3,4]가 배열이고 배열 차원도 변환됩니다.
let one, two, three, four;
[one, two, [three, four]] = [1,2,[3,4]];
console.log([one, two, three, four]);//[1,2,3,4]
⇒ [one, , , four] 형태에서 콤마로 구분하고 변수를 작성하지 않을 경우 인덱스를 건너 띄어 할당합니다.
let one, two, three, four;
[one, , , four] = [1,2,3,4];
console.log([one, two, three, four]);
//[1, undefined, undefined, 4]
let one, rest;
[one, ...rest] = [1,2,3,4];
console.log(one); //1
console.log(rest);//[2,3,4]
let one,three, rest;
[one, ,three ...rest] = [1,2,3,4, 5];
console.log(three); //3
console.log(rest);//[4, 5]