모던 자바스크립트 36장 디스트럭처링 할당

연호·2023년 1월 10일
0

모던자바스크립트

목록 보기
27/28

디스트럭처링 할당

  1. 디스트럭처링 할당 (구조 분해 할당)은 구조화된 배열과 같은 이터러블 또는 객체를 destructuring(비구조화, 구조파괴)하여 1개 이상의 변수에 개별적으로 할당하는 것을 말한다. 배열 디스트럭처링 할당의 대상은 이터러블이어야 하며, 할당 기준은 배열의 인덱스이다. 요소의 개수가 반드시 일치할 필요는 없다.
const arr = [1,2,3];

// 변수 one,two,three를 선언하고 배열 arr를 디스트럭처링하여 할당한다.
// 할당 기준은 배열의 인덱스
const [one, two, three] = arr;

console.log(onw, two, three); // 1 2 3

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

const[c,d] = [1,2,3]
console.log(c,d); // 1 2
  1. 객체 디스트럭처링 할당에서 순서는 의미가 없고 할당 기준은 프로퍼티 키이다.
const user = { firstName: 'gildong', lastName: 'Hong' };

// 변수 lastName, firestName을 선언하고 user 객체를 디스트럭처링하여 할당한다.
// 이때 프로퍼티 키를 기준으로 이루어진다. 순서는 의미가 없다.
// 이는 프로퍼티 축약 표현을 통해 선언한 것이다.
const { lastName, firstName } = user;
// 이 둘은 동치
const { lastName:lastName, firstName:firstName } = user;


console.log(firstName,lastName); // gildong Hong

const { lastName: ln, firstName:fn } = user;
console.log(fn,ln) // gildong Hong
  1. 객체 디스트럭처링 할당은 프로퍼티 키로 필요한 프로퍼티 값만 추출하여 변수에 할당하고 싶을 떄 유용하다.
const str = "Hello";
// String 래퍼 객체로부터 length 프로퍼티만 추출한다.
const { length } = str;
console.log(length); // 5

const todo = { id : 1, content:'HTML', completed: true };
// todo 객체로부터 id 프로퍼티만 추출한다.
const { id } = todo;
console.log(id); // 1
profile
뉴비

0개의 댓글