디스트럭처링 할당

ken6666·2024년 4월 14일
0

JS

목록 보기
27/39

디스트럭처링 할당(구조 분해 할당)은 구조화된 배열과 같은 이터러블 또는 객체를 1개 이상의 변수에 개별적으로 할당하는 것을 말한다.

배열 디스트럭처링 할당

const arr = [1, 2, 3];
const [one, two, three] = arr;

console.log(one, two, three); // 1 2 3
  • 배열 디스트럭처링 할당을 위해서는 할당 연산자 왼쪽에 값을 할당받을 변수를 선언하고 변수를 배열 리터럴 형태로 선언해야한다.
const [a, b] = [1, 2];
console.log(a, b); // 1 2

const [c, d] = [1];
console.log(c, d); // 1 undefined

const [e, f] = [1, 2, 3];
console.log(e, f); // 1 2

const [g, , h] = [1, 2, 3];
console.log(g, h); // 1 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 ]
  • Rest요소 사용 가능하다.

객체 디스트럭처링 할당

const user = { firstName: 'Ungmo', lastName: 'Lee' };


const { lastName, firstName } = user;

console.log(firstName, lastName); // Ungmo Lee
  • 할당 기준은 프로퍼티 키다. 순서는 의미가 없으며 변수이름과 프로퍼티 키가 일치하면 할당된다.
const user = { firstName: 'Ungmo', lastName: 'Lee' };

const { lastName: ln, firstName: fn } = user;

console.log(fn, ln); // Ungmo Lee
  • 객체의 프로퍼티 키와 다른 변수 이름으로 프로퍼티 값을 할당받을수 있다.
const { firstName = 'Ungmo', lastName } = { lastName: 'Lee' };
console.log(firstName, lastName); // Ungmo Lee

const { firstName: fn = 'Ungmo', lastName: ln } = { lastName: 'Lee' };
console.log(fn, ln); // Ungmo Lee
  • 객체 디스트럭처링 할당을 위한 변수에 기본값을 설정할 수 있다.
function printTodo({ content, completed }) {
  console.log(`할일 ${content}${completed ? '완료' : '비완료'} 상태입니다.`);
}

printTodo({ id: 1, content: 'HTML', completed: true });
// 할일 HTML은 완료 상태입니다.
  • 객체를 인수로 전달받는 매개변수 todo에 객체 디스트럭처링 할당을 사용하면 좀 더 간단하고 가독성 좋게 표현할 수 있다.
const user = {
  name: 'Lee',
  address: {
    zipCode: '03068',
    city: 'Seoul'
  }
};


const { address: { city } } = user;
console.log(city); // 'Seoul'
  • address 프로퍼티 키로 객체를 추출하고 이 객체의 city 프로퍼티 키로 값을 추출한다.
// Rest 프로퍼티
const { x, ...rest } = { x: 1, y: 2, z: 3 };
console.log(x, rest); // 1 { y: 2, z: 3 }
  • 객체 디스트럭처링 할당을 위한 Rest 파라미터 적용 가능.

0개의 댓글