구조 분해 할당(Destructuring Assignment)

유연희·2022년 5월 22일
0

구조분해할당이란?

구조분해 할등은 배열 또는 객체가 가진 요소의 값을 변수에 개별적으로 저장하는 방법이다.

배열 구조분해할당

구조분해할당을 이용해 한줄의 코드로 배열의 요소가 변수에 하나씩 할당되는 것을 확인할 수 있다.

const rainbow=["Red","Orange","Yello","Green","Blue"]
const [color1, color2, color3, color4, color5] = rainbow
console.log(color1) //'Red'
console.log(color2) //'Orange'
console.log(color3) //'Yello'
console.log(color4) //'Green'
console.log(color5) //'Blue'

일부 요소만 넣고 싶은 경우에는 변수를 비워주는 방법으로 필요한 요소감 변수에 담아줄 수 있다.

const rainbow=["Red","Orange","Yello","Green","Blue"]
//배열의 첫 번째 요소와 마지막 요소만 변수에 할당.
const [color1, , , , color5] = rainbow
console.log(color1) //'Red'
console.log(color5) //'blue'

스프레드 연산자 ...(변수) 을 이용해 할당하지 않는 나머지 요소들만 모아 하나의 변수에 할당해주는 방법도 있다.

const rainbow=["Red","Orange","Yello","Green","Blue"]
const [color1, ,color3,...colors ] = rainbow
console.log(color1) //'Red'
console.log(color3) //'Yello'
console.log(colors) //[ 'Green', 'Blue' ]

객체 구조분해할당

객체 구조분해할당의 경우 key값을 변수로 사용해 변수에 value 값을 넣을 수 있다. 따라서 배열과 달리 순서가 상관이 없다.

const student = {
name: "영수",
age: 13,
school:"도토리초등학교",
};
const {name, age, school} = student;
console.log(name); // '영수'
console.log(age); // 13
console.log(school); // '도토리초등학교'

객체 구조분해할당 역시 스프레드 연산자 ...(변수)를 통해 할당하지 않은 나머지 객체들을 하나의 변수에 담을 수 있다.

 const student = {
  name: "영수",
  age: 13,
  school:"도토리초등학교",
  gender:"male"
};
//순서가 상관 없다.
const {age, name, ...ect} = student;
console.log(name); // '영수'
console.log(age); // 13
console.log(ect); // { school: '도토리초등학교', gender: 'male' }
profile
developer

0개의 댓글