프로젝트를 하며 심심치 않게 사용했던 부분이 구조분해 할당이다.
MDN을 찾아보니 구조분해 할당에 대한 예제가 어마어마 하다...
구조분해 할당에 대해 알아보자
구조분해 할당
- 구조 분해 할당은 spread 문법을 이용하여 값을 해체한 후, 개별 값을 변수에 새로 할당하는 과정을 말합니다.
분해 후 새 변수에 할당
배열
const [a, b, ...rest] = [10, 20, 30, 40, 50];
// 질문: a, b, rest는 각각 어떤 값인가요?
// a = [10]
// b = [20]
// rest = [30, 40, 50]
기본 변수 할당
let foo = ["one", "two", "three"];
let [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
선언에서 분리한 할당
let a, b;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
기본값
- 변수에 기본값을 할당하면, 분해한 값이 undefined일 때 그 값을 대신 사용합니다.
let a, b;
[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7
함수가 반환한 배열 분석
function f() {
return [1, 2];
}
let a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2
객체
const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
// 질문: a, b, rest는 각각 어떤 값인가요?
// a = {a: 10}
// b = {b: 20}
// rest = {c: 30, d: 40}
새로운 변수 이름으로 할당하기
let o = {p: 42, q: true};
let {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
중첩된 객체 및 배열의 구조분해
let metadata = {
title: "Scratchpad",
translations: [
{
locale: "de",
localization_tags: [ ],
last_edit: "2014-04-14T08:43:37",
url: "/de/docs/Tools/Scratchpad",
title: "JavaScript-Umgebung"
}
],
url: "/en-US/docs/Tools/Scratchpad"
};
let { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
- 왜? console.log(englighTitle) // "Scratchpad"인가?
"englishTitle"이 아니라 englishTitle이라서 "Scratchpad"가 englishTitle에 할당되는 것인가?
for ~ of 반복문과 구조분해
let people = [
{
name: "Mike Smith",
family: {
mother: "Jane Smith",
father: "Harry Smith",
sister: "Samantha Smith"
},
age: 35
},
{
name: "Tom Jones",
family: {
mother: "Norah Jones",
father: "Richard Jones",
brother: "Howard Jones"
},
age: 25
}
];
for (let {name: n, family: { father: f } } of people) {
console.log("Name: " + n + ", Father: " + f);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
함수 매개변수로 전달된 객체에서 필드 해체하기
function userId({id}) {
return id;
}
function whois({displayName: displayName, fullName: {firstName: name}}){
console.log(displayName + " is " + name);
}
let user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
console.log("userId: " + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"
함수에서 객체 분해
function whois({displayName: displayName, fullName: {firstName: name}}){
console.log(displayName + " is " + name);
}
let user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
}
};
whois(user) // 질문: 콘솔에서 어떻게 출력될까요?
// jdoe is John
레퍼런스 : 구조 분해 할당(MDN)
'javaScript' 카테고리의 다른 글
Element와 node의 차이 (0) | 2022.11.22 |
---|---|
DOM(Document Object Model)의 구조 (0) | 2022.11.18 |
spread 문법 사용하기 (0) | 2022.11.17 |
클로저 모듈 패턴에 대해 (0) | 2022.11.17 |
스코프와 클로저 (0) | 2022.11.17 |