在ES6中新增了變量賦值的方式。
數(shù)組解構(gòu)賦值
按照一定的模式,從數(shù)組和對(duì)象中提取值。
let [a, b, c] = [1, 2, 3]
解構(gòu)賦值的重點(diǎn)在于和左側(cè)要和右側(cè)有類似的格式,例如上面的中括號(hào)[ ]
賦值元素可以是任意可遍歷元素
let [a, b, c] = "abc" // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3])
可以跳過(guò)賦值元素
如果想跳過(guò)數(shù)組的某個(gè)元素進(jìn)行賦值,可以使用逗號(hào)實(shí)現(xiàn)。
let [name, , title] = ['John', 'Jim', 'Sun', 'Moon']
console.log( title ) // Sun
使用rest獲取剩下的數(shù)組元素
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"]
console.log(name1) // Julius
console.log(name2) // Caesar
// Note that type of `rest` is Array.
console.log(rest[0]) // Consul
console.log(rest[1]) // of the Roman Republic
console.log(rest.length) // 2
注意:要保證rest放在最后的位置。
默認(rèn)值
如果對(duì)應(yīng)位置沒(méi)有值,則取默認(rèn)值。
let [name = "Guest", surname = "Anonymous"] = ["Julius"]
console.log(name) // Julius (from array)
console.log(surname) // Anonymous (default used)
對(duì)象解構(gòu)賦值
同樣我們?cè)?左側(cè)要有和右側(cè)類似的格式。
let options = {
title: "Menu",
width: 100,
height: 200
}
let {title, width, height} = options
console.log(title) // Menu
console.log(width) // 100
console.log(height) // 200
注:屬性的順序無(wú)需一致。
改變獲取屬性名
對(duì)象的屬性名: 自定義變量名
let {width: w, height: h, title} = options
注:當(dāng)我們自定義變量名后,默認(rèn)的變量名將不可用。
默認(rèn)值
對(duì)應(yīng)位置沒(méi)有值時(shí),取默認(rèn)值。
let options = {
title: "Menu"
}
let {width = 100, height = 200, title} = options
console.log(title) // Menu
console.log(width) // 100
console.log(height) // 200
rest運(yùn)算符
存儲(chǔ)剩余屬性,rest為對(duì)象。
let options = {
title: "Menu",
height: 200,
width: 100
}
let {title, ...rest} = options
// now title="Menu", rest={height: 200, width: 100}
console.log(rest.height) // 200
console.log(rest.width) // 100
嵌套對(duì)象
如果一個(gè)Array或者Object比較復(fù)雜,嵌套了很多層,那么和之前一樣,在=左邊與右邊的結(jié)構(gòu)一致即可。
let options = {
size: {
width: 100,
height: 200
},
items: ["Cake", "Donut"],
extra: true // something extra that we will not destruct
}
// destructuring assignment on multiple lines for clarity
let {
size: { // put size here
width,
height
},
items: [item1, item2], // assign items here
title = 'Menu' // not present in the object (default value is used)
} = options
console.log(title) // Menu
console.log(width) // 100
console.log(height) // 200
console.log(item1) // Cake
console.log(item2) // Donut
注意:此處的size和items僅為結(jié)構(gòu),不是變量。若要保存對(duì)應(yīng)的size,可以這樣。
let {
size},
items: [item1, item2],
title = 'Menu'
} = options