디스트럭처링 할당

김민수·2023년 11월 25일
0
post-thumbnail

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


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

// 값이 없을 경우 undefined
const [c, d] = [, 3];
console.log(c, d) // undefined, 2 

const [e, f] = [4, 5, 6];
console.log(e, f) // 4, 5 

// 기본값 설정 가능, 대신 할당 값이 우선
const [g = 1, h = 2] = [7];
console.log(g, h) // 7, 2

// Rest 요소 ...을 사용할 수 있다.
const [x, ...y] = [1,2,3];
console.log(x, y); // 1, [2, 3]

2. 객체 디스트럭처링 할당

할당 기준은 프로퍼티 키다. 즉, 순서는 의미가 없으며, 선언된 변수 이름과 프로퍼티 키가 일치하면 할당된다.

const user = { firstName: 'minsu', lastName: 'kim' };
const { lastName, firstName } = user;
console.log(lastName, firstName) // kim, minsu

const { lastName2, firstName2 } = { firstName2: 'minsu', lastName2: 'kim' };
console.log(lastName2, firstName2) // // kim, minsu

const user2 = { firstName: 'minsu', lastName: 'kim' };
const { lastName: ln, firstName: fn } = user2;
console.log(fn, ln); // minsu, kim

// length 프로퍼티만 추출 가능
const str = 'test';
const {length} = str;
console.log(length); // 4

// 함수 매개변수에도 사용 가능
function printTodo(todo){
  console.log(`할일 ${todo.content}${todo.completed ? '완료' : '비완료'}`);
}
printTodo({id: 1, content: 'HTML', completed: true}); // 할일 HTML은 완료

//rest 프로퍼티 ... 사용
const {x, ...rest} = {x: 1, y: 2, z: 3};
console.log(x, rest); //1 ,{y: 2, z: 3}

0개의 댓글