36장 디스트럭처링 할당
- 구조화된 배열과 같은 이터러블 또는 객체를 destructuring(비구조화)하여 1개 이상의 변수에 개별적으로 할당하는 것
1. 배열 디스트럭처링 할당
var arr = [1,2,3];
var one = arr[0];
var two = arr[1];
var three = arr[2];
console.log(one, two, three);
const arr = [1,2,3];
const [one, two, three] = arr;
console.log(one, two, three);
1.1 배열 디스트럭처링 사용법
const [x,y] = [1,2];
const [x,y];
const [a,b] = {};
let x,y;
[x,y] = [1,2];
- 배열 디스트럭처링 할당의 기준은 배열의 인덱스
const [a, b] = [1,2];
console.log(a, b);
const [c, d] = [1];
console.log(c, d);
const [e, f] = [1,2,3];
console.log(e, f);
const [g, ,h] = [1,2,3];
console.log(g, h);
const [a,b,c = 3] = [1,2];
console.log(a, b, c);
const [e, f= 10, g =3] = [1,2];
console.log(e, f, g);
const [x, ...y] = [1,2,3];
console.log(x, y);
function parseURL(url = '') {
const parsedURL = url.match(/^(\w+):\/\/([^/]+)\/(.*)$/);
console.log(parsedURL);
if (!parsedURL) return {};
const [, protocol, host, path] = parsedURL;
return { protocol, host, path };
}
const parsedURL = parseURL('https://developer.mozilla.org/ko/docs/Web/JavaScript');
console.log(parsedURL);
2. 객체 디스트럭처링 할당
- ES5에서는 객체의 각 프로퍼티를 객체로부터 디스트럭처링하여 변수에 할당하려면, 프로퍼티 키를 사용해야 했다
var user = { firstName: 'Ed', lastName: 'Lee' };
var firstName = user.firstName;
var lastName = user.lastName;
console.log(firstName, lastName);
const user = { firstName: 'Ed', lastName: 'Lee' };
const { lastName, firstName } = user;
console.log(firstName, lastName);
기본적인 사용 방법
const { lastName, firstName } = { firstName: 'Ed', lastName: 'Lee' };
const { lastName, firstName };
const { lastName, firstName } = null;
const { lastName, firstName } = ['Ed','Lee'];
console.log(lastName, firstName);
- 객체의 프로퍼티 키와 다른 변수 이름으로 프로퍼티 값을 할당 받으려면...
const { lastName, firstName } = user;
const { lastName: lastName, firstName: firstName } = user;
const user = { firstName: 'Ed', lastName: 'Lee' };
const { lastName: ln, firstName: fn } = user;
console.log(fn, ln);
const {firstName = 'Ed', lastName} = {lastName :'Lee'};
console.log(firstName, lastName);
객체 디스트럭처링 할당 응용
- 객체 디스트럭처링 할당은 객체에서 프로퍼티 키로 필요한 프로퍼티 값만 추출하여 변수에 할당하고 싶을 때 유용하다
const str = 'Hello';
const {length} = str;
console.log(length);
const todo ={ id:1, conent:'HTML', completed : true};
const {id} = todo;
console.log(id);
- 객체를 인수로 전달받은 함수의 매개변수에도 사용 가능
function printTodo(todo) {
console.log(`할일 ${todo.content}은 ${todo.completed ? '완료' : '비완료'} 상태입니다.`);
}
printTodo({ id: 1, content: 'HTML', completed: true });
function printTodo({ content, completed }) {
console.log(`할일 ${content}은 ${completed ? '완료' : '비완료'} 상태입니다.`);
}
printTodo({ id: 1, content: 'HTML', completed: true });
- 배열의 요소가 객체인 경우, 배열 디스트럭처링 할당과 객체 디스트럭처링 할당 혼용 가능
const todos = [
{ id: 1, content: 'HTML', completed: true },
{ id: 2, content: 'CSS', completed: false },
{ id: 3, content: 'JS', completed: false }
];
const [, { id }] = todos;
console.log(id);
const user = {
name: 'Lee',
address: {
zipCode: '03068',
city: 'Seoul'
}
};
const { address: { city } } = user;
console.log(city);
const { x, ...rest } = { x: 1, y: 2, z: 3 };
console.log(x, rest);