구조 분해 할당

honeyricecake·2022년 8월 2일
0

자바스크립트

목록 보기
12/20
const user = {
  name: 'table',
  age: 50,
  email: 'hashtable@naver.com'
}

const {name, age, email, address} = user

console.log(name, age, email, address)

구조 분해 할당 이란 위와 같이 user라는 객체 데이터에서 내용을 구조분해해서 원하는 속성들만 꺼내서 사용할 수 있는 개념이 된다.

이는 x = user.name 처럼 변수에 할당하여 사용하는 것과 큰 차이는 없으나

없는 값 대신 사용할 수 있는 기본값을 할당하여 사용할 수 있다는 것에서 큰 차이가 있다.

const user = {
  name: 'table',
  age: 50,
  email: 'hashtable@naver.com'
}

const {name, age, email, address = 'Korea'} = user

console.log(name, age, email, address)

이 때 address는 undefined가 아닌 'Korea'가 출력된다!!

배열도 이런 식으로 구조 분해 할당을 할 수 있다.
배열은 구조 분해 할당을 할 때는 대괄호를 써야한다.

또한 꺼내 올 때는 name으로 꺼내오지만 다른 이름으로 변수를 쓰고 싶다면 아래와 같이 쓸 수 있다.

const user = {
  name: 'table',
  age: 50,
  email: 'hashtable@naver.com'
}

const {name: kind, age, email, address} = user

console.log(kind, age, email, address)

배열 구조 분해 할당 응용

ex.

const language = ['C', 'Java', 'Python', 'JavaSpring']
const [,x,,,y = 'C++'] = language
console.log(x,y)

위와 같이 쓰지 않는 항목은 할당하지 않기 위해 변수를 적지 않을 수 있고,
배열의 구조 분해 할당에서도 없는 경우에 대비하여 기본값을 할당할 수 있다.

const language = ['C', 'Java', 'Python', 'JavaSpring', 'Carbon']
const [,x,,,y = 'C++'] = language
console.log(x,y)

이렇게 하면 콘솔에 C++ 대신 Carbon이 출력되는 것을 볼 수 있다.

0개의 댓글