💡 구조분해할당 (Destructuring assignment)
- 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게하는 JS 표현식
기본 문법
배열 구조 분해
const rgb = [255, 200, 0];
const [red, green, blue] = rgb;
console.log(`R: ${red}, G: ${green}, B: ${blue}`);
const [red, green, blue, novalue, yesvalue="defaultVal"] = rgb;
console.log(novalue,yesvalue)
const [,, blue] = rgb;
console.log(blue)
const color = ['#FF00FF', [255, 0, 255]];
const [hex, [red, green, blue]] = color;
const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const [red,, yellow, ...otherColors] = rainbow;
console.log(otherColors);
- ⓐ 변수=값의 형태를 띄고 rgb 배열의 index순으로 값이 변수에 들어간다.
- ⓑ 만약에 변수 > array 값 인 경우에 default value가 없는 경우 undefined가 나온다.
- ⓒ 만약에 array item 중 변수를 할당할 필요가 없는 경우 콤마를 통해 건너띄기가 가능하다.
객체 구조 분해
const person = {
name: '홍길동',
age: 30
}
const { name, age } = person
const { name: manName, age: manAge } = person;
const { name, age, job } = person;
console.log(job)
const person = {
name: '홍길동',
info: {
school: '홍초등학교',
phone: '02-000-0000'
}
}
const {info, info: {school, phone}} = person
console.log(info)
console.log(school,phone)