본문 바로가기

프론트엔드 공부/javscript

구조분해할당(Destructing assignment) - 객체,배열

//구조분해할당(Destructing assignment)
//객체내 key 값을 변수화하여 사용

// 변수내 key 값이 undefined인 경우의 값은 default 값을 구조 분해할당 변수
//내에서 지정할 수도 있음 

 

//구조분해할당(Destructing assignment)
//객체내 key 값을 변수화하여 사용

const user = {
  name: 'minji',
  age: 31,
  email : 'minji@gmail.com'
}

const {name,age : weight, address = 'korea'} = user
console.log(`사용자의 이름은 ${name}입니다`);
console.log(weight); //20
console.log(address); //korea
//사용자의 이름은 minji입니다
//user.name  user['name'] 과 동일
// undefined인 경우의 값은 default 값을 구조 분해할당 변수
//내에서 지정할 수도 있음 
//구조분해할당 - 배열
//배열의 구조분해할당은 순서대로 추출되는 특성이 있다 

const fruits = ['apple','banana','cherry']
const [a,b,c,d] = fruits;
console.log(a,b,c,d) ;//apple banana cherry

////cherry만 추출하고 싶을 경우
//const [,,b] = fruits;
//console.log(b) //cherry