구조 분해 할당 구문 (destructuring assignment)은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담아 원할 때 원하는 변수에 출력할 수 있는 자바스크립트 표현식이다.
var foo = ["one", "two", "three"];
var [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
변수의 선언이 분리되어도 구조 분해를 통해 값을 할당할 수 있다.
var a, b;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
하나의 구조 분해 표현식만으로도 두 변수의 값을 교체할 수 있다.
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
아래 예제에서 f()
는 출력으로 배열 [1, 2]을 반환하는데, 하나의 구조 분해만으로 값을 분석할 수 있습니다.
function f() {
return [1, 2];
}
var a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2
//일부 반환 값 무시하기
function f() {
return [1, 2, 3];
}
var [a, , b] = f();
console.log(a); // 1
console.log(b); // 3
//모든 반환 값 무시하기
[,,] = f();
배열을 구조 분해할 경우, 나머지 구문을 이용해 분해하고 남은 부분을 하나의 변수에 할당할 수 있다.
var [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
또 다른 예시를 살펴보자.
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
구조 분해를 통해 변수의 선언과 분리하여 변수에 값을 할당할 수 있다.
원래라면 var {a, b} = {a:1, b:2}
일 것이다.
이 경우 아래의 2가지를 확실하게 해주어야 한다.
var a, b;
({a, b} = {a: 1, b: 2});
객체로부터 해체된 값이 undefined
인 경우, 변수에 기본값을 할당할 수 있다.
var {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5
var {a: aa = 10, b: bb = 5} = {a: 3};
console.log(aa); // 3
console.log(bb); // 5