구조 분해 할당은 배열이나 객체의 속성을 분해시켜서 그 값을 변수에 바로 담을 수 있게 해주는 JavaScript 표현식이다.
const numArray = [1, 2, 3, 4, 5];
const [one, two, three, four, five] = numArray;
console.log(one, two, three, four, five);
//output : 1 2 3 4 5
함수의 파라미터 기본값을 설정하듯이 변수에 담길 값의 기본값을 설정해줄 수 있다. 객체도 분해한 값이 undefined
인 경우 똑같이 가능하다.
const numArray = [100, 200, 300];
const [one=1, two=2, three=3, four=4, five=5] = numArray;
console.log(one, two, three, four, five);
//output : 100 200 300 4 5
일반적으로 두 변수에 담긴 값을 교환하려면 하나의 임시 변수가 필요하다.
let a = 1;
let b = 2;
a = b;
b = a;
// b의 값(2)이 a에 할당되고, a의 값(할당된 2)가 다시 b에 할당된다.
console.log(a, b); // 2 2
//---------------------------------------------------------
let a = 1;
let b = 2;
let c; // 임시변수 c
c = a;
a = b;
b = c;
console.log(a, b) // 2 1
구조 분해 할당을 사용하면 단 한 줄의 구조 분해 표현식만으로 변수값을 교환할 수 있다.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
배열을 구조 분해할 때, rest parameter
를 이용해 남은 부분을 변수에 담을 수 있다.
let [a, ...res] = [1, 2, 3];
console.log(a); // 1
console.log(res); // [2, 3]
주의!
나머지 구문 뒤에 ,(쉼표)가 있으면 문법 오류가 발생한다.let [a, ...res,] = [1, 2, 3]; // SyntaxError: rest element may not have a trailing comma
let obj = {name: "aggie", age: 26};
const {name, age} = obj;
console.log(name) // "aggie"
console.log(age) // 26
배열에서는 선언 없는 할당을 그냥
let a, b;
let myArr = [1, 2];
[a, b] = myArr;
이렇게 하면 되지만, 객체는 다르다. 객체도 위와 같이
let a, b;
let myObj = {a: 1, b: 2};
{a, b} = myObj;
이렇게 해버리면 좌변의 {a, b}
가 객체가 아닌 블록으로 간주되기 때문
객체는 선언 없는 할당을 할 때 전체를 ()
괄호로 감싸주면 된다.
({a, b} = myObj});
객체로부터 속성을 분해하여 가져올 때 다른 변수의 이름에 할당할 수 있다.
let myObj = {a: 1, b: 2};
let {a: one, b: two} = myObj;
console.log(one); // 1
console.log(two); // 2
객체 구조 분해 시, 새로운 이름을 설정한 뒤 =
을 사용해 기본값을 설정해줄 수 있다.
let myObj = {a: 100, b: 200};
let {a: one = 1, b: two = 2, c: three = 3} = myObj;
console.log(one); // 100
console.log(two); // 200
console.log(three); // 3
참... 진짜 자바스크립트는 너무 강력한 것 같다..
객체에 키가 없는데도 그냥 만들어버리고 구조 분해 할당 하면서 이름도 바꿔버리고 기본값까지 담아서 값까지 할당시켜버려...
그렇군요!