[์๋ฐ์คํฌ๋ฆฝํธ] ๊ตฌ์กฐ ๋ถํด ํ ๋น
์ฐธ๊ณ ์๋ฃ: ์ธํ๋ฐ ์๋ฐ์คํฌ๋ฆฝํธ ์ด๊ธ๊ฐ์
Javascript ES6+ ์ ๋๋ก ์์๋ณด๊ธฐ - ์ด๊ธ - ์ธํ๋ฐ | ๊ฐ์
ES6+ ์ ๋๋ก ์์๋ณด๊ธฐ ๊ฐ์ข๋ Javascirpt์ ES6 ๋ฐ ์ดํ์ ํ์ค ECMAScript ๋ช ์ธ์ ๋ํ์ฌ ์ด๋ก ์ ๋ฐํ์ผ๋ก ES5์ ๋ฌ๋ผ์ง ์ ๋ฐ ๊ฐ๋ ๊ณผ ๋์ ์๋ฆฌ๋ฅผ ๊น์ด ์๊ฒ ์๋ ค๋๋ฆฝ๋๋ค., Javascript ES6+๋ ๋ญ๊ฐ ๋ค๋ฅผ๊น?
www.inflearn.com
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]
- ์์ ์ฝ๋๋ e ์ ์ธํ ๋, f์ ์ธ ์๋๋๋ฐ ์ธ์ฉ๋๊ณ ์์ผ๋, TDZ์ ๊ฑธ๋ฆฌ๊ฒ ๋๋ค.
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๋ผ๊ณ ์ ํ์ฌ ๊ฐ์ ๊ฐ์ ธ์ฌ ์ ์๋ค.