본문 바로가기

Front-End/JavaScript

[JavaScript] 구조 분해 할당(Destructuring assignment)

구조 분해 할당 (Destructuring assignment)

: 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식

: 할당문의 좌변에서 사용하여, 원래 변수에서 어떤 값을 분해해 할당할지 정의한다.

 

1) 배열 구조 분해

기본 변수 할당
const numbers = [1, 2];
const [x, y] = numbers;
console.log(x); //1
console.log(y); //2

 

변수에 기본값 할당
: 분해한 값이 undefined일 경우 기본값을 대신 사용할 수 있다.
let a, b;
[a=5, b=7] = [1];
console.log(a); //1
console.log(b); //7

 

변수 값 교환
let a = 1;
let b = 3;

[a, b] = [b, a];
console.log(a); //3
console.log(b); //1

 

일부 반환값 무시
: 할당하고자 하는 변수의 개수와 분해하고자 하는 배열의 길이가 달라도 에러가 발생하지 않는다.
: 할당할 값이 없으면 undefined로 취급된다.
const numbers = [1, 2, 3, 4, 5];
const [x, y] = numbers;
console.log(x); //1
console.log(y); //2
const [a,b,c,d,e,f] = numbers;
console.log(e); //5
console.log(f); //undefined

 

나머지 할당
: 나머지 구문을 활용해 분해하고 남응ㄴ 부분을 하나의 변수에 할당할 수 있다.
const [a, ...b] = [1, 2, 3];
console.log(a); //1
console.log(b); //[2, 3]

 

 

2) 객체 구조 분해

기본 할당weig
: 할당 순서는 상관없다.
var obj1 = {weight: 50, height: 165};
var {height, weight} = obj1;

console.log(weight); // 50
console.log(height); // 165

 

새로운 변수 이름으로 할당
: 객체의 원래 속성명과 다른 이름의 변수에 할당이 가능하다.
var obj1 = {weight: 50, height: 165};
var {weight: w, height: h} = obj1;

console.log(w); // 50
console.log(h); // 165

 

기본값 할당
: 객체로부터 해체된 값이 undefined인 경우, 변수에 기본값을 할당할 수 있다.
: 기본값 할당과 새로운 변수명으로의 할당을 동시에 할 수 있다.
var {a: aa = 10, b = 5} = {a: 3};

console.log(aa); // 3
console.log(b); // 5

 

 

3) 중첩된 객체 및 배열의 구조 분해

const obj1 = {
  name: "홍길동",
  size:{
    weight: 50,
    height: 165
  }
};

const {
  name: fullName,
  size:{
    weight,
    height: h
  }
} = obj1;

console.log(fullName); //홍길동
console.log(weight); //50
console.log(h); //165

 

 

*참고 자료*

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment