- Published on
Javascript - Destructuring Assignment
- Author
- Name
- yceffort
๊ตฌ์กฐ ๋ถํด ํ ๋น
๊ตฌ์กฐ ๋ถํด ํ ๋น์ ๋ฐฐ์ด์ด๋ ๊ฐ์ฒด์ ์์ฑ์ ๋ง๊ทธ๋๋ก ๋ถํดํ์ฌ, ๋ถํด ํ ๊ฐ์ ๊ฐ๋ณ๋ณ์์ ๋ด์ ์ ์๊ฒ ๋์์ฃผ๋ ํํ์์ด๋ค.
let a, b, rest
;[a, b] = [10, 20]
console.log(a) // 10
console.log(b) // 20
// rest ํจํด์ ์ด์ฉํ์ฌ ๋๋จธ์ง๋ฅผ ๋ชจ๋ ํ ๋น ๋ฐ์ ์ ์๋ค.
;[a, b, ...rest] = [10, 20, 30, 40, 50]
console.log(a) // 10
console.log(b) // 20
console.log(rest) // [30, 40, 50]
// ๊ฐ์ฒด ๋ฆฌํฐ๋ด ์์์ ๊ตฌ์กฐ ๋ถํด ํ ๋น์ ํ๊ธฐ ์ํด์๋, ๊ฐ์ฒด ๋ฆฌํฐ๋ด ํ์๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก { }๋ก ํ๊ธฐํ๋ฉด ๋๋ค.
;({a, b} = {a: 10, b: 20})
console.log(a) // 10
console.log(b) // 20
;({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40})
console.log(a) // 10
console.log(b) // 20
console.log(rest) // {c: 30, d: 40}
function f() {
return [1, 2]
}
var a, b
;[a, b] = f()
console.log(a) // 1
console.log(b) // 2
// ๊ฐ์ ์๋ ์ฒ๋ผ ๋ฌด์ํ ์๋ ์๋ค.
function f() {
return [1, 2, 3]
}
var [a, , b] = f()
console.log(a) // 1
console.log(b) // 3
๊ฐ์ฒด ๊ตฌ์กฐ ๋ถํด
var o = {p: 42, q: true}
var {p, q} = o
console.log(p) // 42
console.log(q) // true
var o = {p: 42, q: true}
var {p: foo, q: bar} = o
// p์ q๋ ๋ฌด์๋๋ค.
console.log(foo) // 42
console.log(bar) // true
var metadata = {
title: 'Scratchpad',
translations: [
{
locale: 'de',
localization_tags: [],
last_edit: '2014-04-14T08:43:37',
url: '/de/docs/Tools/Scratchpad',
title: 'JavaScript-Umgebung',
},
],
url: '/en-US/docs/Tools/Scratchpad',
}
var {
title: englishTitle,
translations: [{title: localeTitle}],
} = metadata
console.log(englishTitle) // "Scratchpad"
console.log(localeTitle) // "JavaScript-Umgebung"
var people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith',
},
age: 35,
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones',
},
age: 25,
},
]
for (var {
name: n,
family: {father: f},
} of people) {
console.log('Name: ' + n + ', Father: ' + f)
}
function userId({id}) {
return id
}
function whois({displayName: displayName, fullName: {firstName: name}}) {
console.log(displayName + ' is ' + name)
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
var user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe',
},
}
console.log('userId: ' + userId(user)) // "userId: 42"
whois(user) // "jdoe is John"
let key = 'z'
let {[key]: foo} = {z: 'bar'}
console.log(foo) // "bar"
{
innerHeight
} // {innerHeight: 441}
{
innerHeight
} // 441
์ฌ๊ธฐ์์ //๋ ์ ์ญ๊ฐ์ฒด window
์ผ ๊ฒ์ด๋ค.
๊ฐ์ฒด ๋ฆฌํฐ๋ด ํ๊ธฐ๋ฒ๊ณผ JSON์ ์ฐจ์ด
- JSON์ "key": value ๊ตฌ๋ฌธ๋ง ํ์ฉํ๋ค.
key
๊ฐ์ ํฐ ๋ฐ์ดํ๋ก ๋ฌถ์ฌ ์์ด์ผํ๋ค. ๊ทธ๋ฆฌ๊ณ ๊ฐ์ ๋จ์ถ(๋ช )์ผ ์๋ ์๋ค. - JSON์์ ๊ฐ์ ๋ฌธ์์ด, ์ซ์, ๋ฐฐ์ด,
true
,false
,null
๋๋ ๋ค๋ฅธ JSON๊ฐ์ฒด๋ง ๊ฐ๋ฅํ๋ค. - ํจ์๋ JSON๊ฐ์์ ํ ๋น๋ ์ ์๋ค.
Date
๊ฐ์ฒด๋ JSON.parse()๋ฅผ ๊ฑฐ์น๊ณ ๋๋ฉด ๋ฌธ์์ด์ด ๋๋ค.