공부공부/JS 딥다이브

[js 딥다이브] 36장 디스트럭처링 할당

고생쨩 2024. 2. 18. 09:58
728x90

디스트럭처링 할당

배열 디스트럭처링 할당

const arr = [1, 2, 3];
// ES6 배열 디스트럭처링 할당
// 변수 one, two, three를 선언하고 배열 arr을 디스트럭처링하여 할당한다.
// 이때 할당 기준은 배열의 인덱스다.
const [one, two, three] = arr;
console.log(one, two, three); // 1 2 3
// 기본값
const [a, b, c = 3] = [1, 2];
console.log(a, b, c); // 1 2 3
// 기본값보다 할당된 값이 우선한다.
const [e, f = 10, g = 3] = [1, 2];
console.log(e, f, g); // 1 2 3
// Rest 요소
const [x, ...y] = [1, 2, 3];
console.log(x, y); // 1 [ 2, 3 ]

객체 디스트럭처링 할당

할당 기준은 프로퍼티 키

const user = { firstName: 'Ungmo', lastName: 'Lee' };
// 이때 프로퍼티 키를 기준으로 디스트럭처링 할당이 이루어진다. 순서는 의미가 없다.
const { lastName, firstName } = user;
console.log(firstName, lastName); // Ungmo Lee
const { lastName, firstName } = user;
// 위와 아래는 동치다.
const { lastName: lastName, firstName: firstName } = user;
const { firstName: fn = 'Ungmo', lastName: ln } = { lastName: 'Lee' };
console.log(fn, ln); // Ungmo Lee

중첩 객체

const user = {
 name: 'Lee',
 address: {
    zipCode: '03068',
 city: 'Seoul'
 }
};
// address 프로퍼티 키로 객체를 추출하고 이 객체의 city 프로퍼티 키로 값을 추출한다.
const { address: { city } } = user;
console.log(city); // 'Seoul'

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.