참고자료: 인프런 자바스크립트 초급강의
1. 해체할당
1-1. 배열 할당
var colors = ['red', 'white', 'orange']
var first = colors[0]
var second = colors[1]
var third = colors[2]
console.log(first, second, third)
//해체할당
const colors = ['red', 'white', 'orange']
const [first, second, third] = colors
console.log(first, second, third)
응용해서
let [ , , third] = colors;
let[ , second] = colors;
이렇게도 가능, 자기가 원하는 몇 번째 인자만
그럼 만약
const [ , , third, fourth] = colors;
console.log(fourth); //undefined
매칭할게 없으면 undefined로 출력된다 !
나머지 연산으로도 가능
const arr = [1, 2, 3, 4, 5]
const [ a, ...b ] = arr
const [ , , ...c ] = arr
나아가서,
const [c, d = c * 2] = [5]
console.log(c, d);
//result
c: 5 d: 10
const [e = f, f] = [undefined, 10]
위에 코드는 TDZ에 걸림. e선언할 때, f선언 안됐는데 인용되고 있으니.
const arr = [1, [2, [3, 4], 5], 6]
const [a, [b, [ , c], ], d] = arr
console.log(a, b, c, d)
똑같은 모양으로 적으면 다 추출돼 !
- 두개 인자 값 바꾸고 싶을 때
let a = 10;
let b = 20;
[a, b] = [b, a]
1-2. 객체 할당 ⭐⭐⭐⭐⭐
const iu = {
name : '아이유',
age : 25,
gender : 'female'
}
const {
name,
age,
gender
} = iu
console.log(name, age, gender)
조금 어렵게 간다면,
const loginInfo = {
device: {
createdAt: '2017-12-06T00:14:04+0000',
deviceId: '0000000000004Vx',
deviceType: 'desktop'
},
user: {
createdAt: '2017-03-08T18:00:28+0000',
email: 'power4ce@gmail.com',
name: '정재남',
nickname: 'gomugom',
phoneNumber: '010-9185-9155'
}
}
//객체 해체
const {
device: {
createdAt,
deviceId
},
user: {
name,
nickname,
phoneNumber: phone
}
} = loginInfo
- default parameter와 연동 가능
const phone = {
name : 'iPhone',
color : undefined
}
const {
name: n,
version: v = '6+',
color: c = 'silver'
} = phone
console.log(n, v, c)
//result
iPhone 6+ silver
iPhone은 그대로 출력
version 인자가 없어서 default 값인 6+ 출력
color는 undefined이기 때문에 default 값 silver 출력
실제 현업에서 많이 사용하는 예
const deliveryProduct = {
orderedDate: '2018-01-15',
estimatedDate: '2018-01-20',
status: '배송중',
items: [
{name: '사과', price: 1000, quantity: 3},
{name: '배', price: 1500, quantity: 2},
{name: '딸기', price: 2000, quantity: 4}
]
}
const {
estimatedDate: esti,
status,
items: [ , ...products]
} = deliveryProduct
console.log(esti, status, products)
코드 의미)
estimateDate 이름 너무 길어 esti로 바꿀래
status 다 가져와
item은 첫번째 프로퍼티 제외하고는 나머지는 다 products라고 칭할래
끝!
'자바스크립트의 정석 🟡' 카테고리의 다른 글
[자바스크립트] closure 정리 ✨ (0) | 2024.01.24 |
---|---|
[자바스크립트] this 정리 ✨ (1) | 2024.01.23 |
자바스크립트 - Function etc (0) | 2023.09.19 |
자바스크립트 - arrow function (0) | 2023.09.19 |
자바스크립트 - rest parameter, spread operator (0) | 2023.09.18 |