FrontEnd/Javascript
[ Javascript ] 구조 분해 할당
jimin-log
2023. 8. 14. 16:15
구조분해할당 = 비구조화 할당
원하는 속성들만 꺼내서 변수로 만들어 사용할 수 있다는 장점이 있다.
1. 구조분해할당 객체 사용
const user= {
name ='Heropy',
age =85,
email ='thesecon@gmail.com'
}
const {name, age, email, address} = user
console.log(`사용자의 이름은 ${name}입니다.`);
//결과값 : 사용자의 이름은 Heropy입니다.
console.log(`${name}의 나이는 ${age}입니다.`);
// 결과값 : Heropy의 나이는 85입니다.
console.log(`${name}의 이메일은 ${email}입니다.`);
// 결과값 : Heropy의 이메일은 thesecon@gmail.com 입니다.
console.log(address); //결과값 : undefinde
속성이 없을 시 undefinde또는 에러가 날 수 있는데, 기본값을 지정해줄 수 있다.
const {name, age, email, address ='korea' } = user
console.log(address) // korea
변수의 명을 변경 하고 싶을때
1.
const {name, age, email, address ='korea' } = user
const heropy = name
2.
const {name:heropy , age, email, address ='korea' } = user
const heropy = name
console.log(`사용자의 이름은 ${heropy}입니다.`);
2. 구조분해할당 배열 사용
배열 데이터도 사용가능하다.
객체와 달리 인덱스 순서대로 꺼내와진다.
const fruits = ['Apple','Banana','Cherry'];
const [a,b,c,d] = fruits
console.log(a,b,c,d)
//출력값 : Apple Banana Cherry undefind
원하는 값만 추출하고 싶을때
const fruits = ['Apple','Banana','Cherry'];
const [,b] = fruits
console.log(b)
//출력값 : Banana