구조 분해 할당(Destructuring assignment) 다른말로 비구조화 할당 이라고도 부릅니다.
const user = {
name: 'Heropy',
age: 85,
email: 'thesecon@gmail.com'
}
const { name, age, email, address } = user;
console.log(`사용자의 이름은 ${name}입니다.`);
// 사용자의 이름은 Heropy입니다.
console.log(`${name}의 나이는 ${age}세입니다.`);
// Heropy의 나이는 85세입니다.
console.log(`${name}의 이메일 주소는 ${email}입니다.`);
// Heropy의 이메일 주소는 thesecon@gmail.com입니다.
console.log(address);
// undefined
const { name, age, email, address = 'Korea'} = user;
console.log(address); // Korea
undefinded
대신 기본값으로 지정한 Korea
가 출력됐습니다.const user = {
name: 'Heropy',
age: 85,
email: 'thesecon@gmail.com',
address: 'USA'
}
const { name, age, email, address = 'Korea'} = user;
console.log(address); // USA
Korea
가 무시되고 USA
가 출력됩니다.const user = {
name: 'Heropy',
age: 85,
email: 'thesecon@gmail.com',
address: 'USA'
}
const { name: heropy, age, email, address = 'Korea'} = user;
console.log(heropy); // 'Heropy'
name: heropy
라고 명시하여 꺼내오는 속성은 name
으로, 사용하고 싶은 변수 이름은 heropy
로 지정할 수 있습니다.const fruits = ['Apple', 'Banana', 'Cherry'];
const [a, b, c, d] = fruits;
console.log(a, b, c, d);
// Apple Banana Cherry undefined
{}
였지만, 지금은 배열을 구조분해 하기 때문에 []
로 명시합니다.a, b, c, d
에 순서대로 'Apple', 'Banana', 'Cherry', undefinded
가 들어갔습니다.예) Apple은 추출하지 않고 Banana만 추출하고 싶을 경우,
const fruits = ['Apple', 'Banana', 'Cherry'];
const [, b] = fruits;
console.log(b);
// Banana
예2) Cherry만 출력하고 싶은 경우,
const fruits = ['Apple', 'Banana', 'Cherry'];
const [, , a] = fruits;
console.log(a);
// Cherry