구조 분해 할당

옛슬·2022년 1월 12일
0
post-thumbnail

💡 구조분해할당 (Destructuring assignment)

  • 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게하는 JS 표현식

기본 문법

배열 구조 분해

const rgb = [255, 200, 0];

// ⓐ array destructuring
const [red, green, blue] = rgb;
console.log(`R: ${red}, G: ${green}, B: ${blue}`); // R: 255, G: 200, B: 0

// ⓑ Assign default values
const [red, green, blue, novalue, yesvalue="defaultVal"] = rgb; 
console.log(novalue,yesvalue) // undefined , 'defaultVal'

// ⓒ Skip items
const [,, blue] = rgb;
console.log(blue) // 0

// ⓓ Nested Array Destructuring
const color = ['#FF00FF', [255, 0, 255]];
const [hex, [red, green, blue]] = color;

// ⓔ Rest Items
const rainbow = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const [red,, yellow, ...otherColors] = rainbow;
console.log(otherColors); // ['green', 'blue', 'indigo', 'violet']
  • ⓐ 변수=값의 형태를 띄고 rgb 배열의 index순으로 값이 변수에 들어간다.
  • ⓑ 만약에 변수 > array 값 인 경우에 default value가 없는 경우 undefined가 나온다.
  • ⓒ 만약에 array item 중 변수를 할당할 필요가 없는 경우 콤마를 통해 건너띄기가 가능하다.

객체 구조 분해

const person = {
	name: '홍길동',
  	age: 30
}

const { name, age } = person

// Assign different name
const { name: manName, age: manAge } = person;

// Assign default values
const { name, age, job } = person;
console.log(job) // undefined 

// Nested Array Destructuring
const person = {
	name: '홍길동',
  	info: {
    	school: '홍초등학교',
      phone: '02-000-0000'
    }
}

const {info, info: {school, phone}} = person
console.log(info) // {'school': '홍초등학교', 'phone': '02-000-0000'}
console.log(school,phone) // "홍초등학교" "02-000-0000"
profile
웹 퍼블리셔입니다💓

0개의 댓글