구조 분해 할당 (비구조화 할당)
객체
const user= {
name: 'flyda',
age: 85,
email: 'dlapdlf@gamil.com'
}
const {name, age, email, address} = user
console.log(`사용자 이름 ${name}`)//사용자 이름 flyda
console.log(`사용자 나이 ${age}`)//사용자 나이 85
console.log(`사용자 이메일 ${email}`)//사용자 이메일 dlapdlf@gamil.com
console.log(`사용자 주소 ${address}`)//사용자 주소 undefined
//정의되어 있지 않으면 undefined
// user.address와 user['address'] 같이 인덱싱 방식으로도 사용할 수 있다.
원하는 key값만 가지고 와서 사용할 수도 있다
const user= {
name: 'flyda',
age: 85,
email: 'dlapdlf@gamil.com'
}
const {name, age, address} = user
console.log(`사용자 이름 ${name}`)//사용자 이름 flyda
console.log(`사용자 나이 ${age}`)//사용자 나이 85
console.log(`사용자 이메일 ${user.email}`)//사용자 이메일 dlapdlf@gamil.com
값이 없는 경우에는 기본값이 출력되도록 설정해 줄 수 있다. 자주 사용되는 것은 아니지만 필요함!
const user= {
name: 'flyda',
age: 85,
email: 'dlapdlf@gamil.com'
}
const {name, age= 4, address='Korea'} = user
console.log(`사용자 이름 ${name}`)//사용자 이름 flyda
console.log(`사용자 나이 ${age}`)//사용자 나이 85
console.log(`사용자 이메일 ${user.email}`)//사용자 이메일 dlapdlf@gamil.com
console.log(`사용자 주소 ${address}`)//사용자 주소 Korea
name: 'flyda',
age: 85,
email: 'dlapdlf@gamil.com'
}
const {name: flyfly, age, address='Korea'} = user
//꺼내 오는 것은 key의 이름으로 꺼내오지만, 활용을 flyfly라는 이름으로 할때!
console.log(`사용자 이름 ${flyfly}`)//사용자 이름 flyda
console.log(`사용자 나이 ${age}`)//사용자 나이 85
console.log(`사용자 이메일 ${user.email}`)//사용자 이메일 dlapdlf@gamil.com
console.log(`사용자 주소 ${address}`)//사용자 주소 Korea
배열
배열에서도 구조 분해 할당을 사용할 수 있다.
const fruits = ['apple', 'banana', 'cherry']
const [a,b,c,d] = fruits
console.log(a,b,c,d)//apple banana cherry undefined
만약 바나나나, 체리만 추출하고 싶다면!! 순서대로 추출하기 때문에 쉼표로 순서를 나타내 준다
const fruits = ['apple', 'banana', 'cherry']
const [,b] = fruits
console.log(b)//banana
const [,,c] = fruits
console.log(c)//cherry'핀테크 서비스 프론트엔드 개발자 취업 완성 2기 > JS' 카테고리의 다른 글
| [JS] Lodash (_.) (0) | 2022.04.28 |
|---|---|
| [JS] 데이터 - 객체 Object (0) | 2022.04.26 |
| [JS] 데이터 - 전개 연산자 (0) | 2022.04.26 |
| [JS] 데이터 - 데이터 불변성 (Immutability) (0) | 2022.04.26 |
| [JS] 데이터 - 얕은복사(Shallow copy) & 깊은 복사(Deep copy) (0) | 2022.04.26 |
댓글