🪕
디스트럭처링 할당
- 구조화된 배열과 같은
이터러블
or 객체
를 destructring 하여 1개 이상의 변수에 개별적으로 할당하는 것을 말함
배열 디스트럭처링 할당
- 변수의 개수와 이터러블의 요소 개수가 반드시 일치할 필요는 없음
Rest 요소(Rest Element)
- Rest 파라미터와 마찬가지로 반드시 마지막에 위치해야 함
객체 디스트럭처링 할당
- ES6 에서 객체 디스트럭처링 할당은 객체의 각 프로퍼티를 객체로부터 추출하여 1개 이상의 변수에 할당함. 이때 할당 기준은
프로퍼티 키
임 - 즉,
프로퍼티 키
와 변수이름
이 일치하면 해당 값이 변수에 할당됨 ( 여기에서 순서는 의미가 없음 )
객체의 프로퍼티 키와 다른 변수 이름으로 할당받고 싶을 때
기본값 설정
사용 예시
함수 매개변수에서 사용
중첩객체
Rest 프로퍼티
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
const [ x, ...y] = [1, 2, 3];
console.log(x, y); // 1, [2, 3]
// ES5
var user = { firstName : 'Ungmo', lastName: 'lee' };
var firstName = user.firstName;
var lastName = user.lastName;
console.log(firstName, lastName);
// ES6
const user = { firstName: 'Ungmo', lastName: 'lee' };
const { lastName, firstName } = user;
const { lastName, firstName } = user;
// 위와 아래는 동치
const { lastName : lastName, firstName : firstName } = user;
const { lastName: ln, firstName: fn } = user;
console.log(fn, ln); // Ungmo lee
객체의 프로퍼티 키와 다른 변수 이름으로 프로퍼티 값을 할당받고 싶을 때const { lastName: ln, firstName: fn = 'Ungmo' } = { lastName : 'Lee' };
console.log(fn, ln); // Ungmo lee
const str = 'Hello';
const { length } = str;
console.log(length); // 5
const todo = { id : 1, content : 'HTML', completed : true };
const { id } = todo;
console.log(id); // 1
필요한 프로퍼티 값만 추출하여 변수에 할당하고 싶을 때 유용function printTodo( { content, completed }) {
console.log(`할일 ${content}은 ${completed ? '완료' : '비완료' } 상태입니다.`);
}
printTodo({ id : 1, content : 'HTML', completed : true });
함수의 매개변수에서 객체 디스트럭처링 할당을 이용할 수 있음const user = {
name : 'Lee',
address : {
zipCode : '03006',
city : 'Seoul',
}
};
const { address : { city }} = user;
console.log(city); // Seoul
const { x, ...rest } = { x : 1, y : 2, z : 3 };
console.log(x, rest); // 1 { y : 2, z : 3 }