구조분해할당

김영후·2022년 7월 12일
0

변수를 할당할 때 여러 번 재할당 하려면 번거롭다.

그래서 구조분해할당을 통해 쉽게 재할당한다.

배열의 구조분해할당

const classamtes = ['철수','영희','훈이']

이것을 그냥 재할당 해보면

const child1 = classmates[0];
const child2 = classmates[1];
const child3 = classmates[2];

구조분해할당으로 재할당하면

const {child1, child2, child3} = classmates;

객체의 구조분해할당

const user = {
name : '철수'
age : 13,
school : '다람쥐초등학교'
createdAt : '2010-09-07'
}

기존에는 .value (dot notation)을 활용해 value값을 가져왔다.

const name = user.name
const age = user.age
const school = user.school
const createdAt = user.createdAt

구조분해할당으로 재할당하면

const {name, age, school, createdAt} = user

배열과 객체의 구조분해할당이 다른 점은


배열을 구조분해할당 하는 경우

배열의 순서가 매우 중요하다



객체를 구조분해할당 하는 경우

객체 안의 key 값을 가져와 할당을 해준다. 순서는 상관없다.

profile
https://poagg.tistory.com/ 로 이전합니다.

0개의 댓글