在Arrow Functions旁邊,這是我天天使用最多的ES6功能。ES6 Destructuring不是一個新功能,而是一種新的賦值語法,它容許您快速從對象屬性和數組中解壓縮值並將它們分配給單個變量。es6
var profile = {name:'George', age:39, hobby:'Tennis'}<font></font>json
var {name, hobby} = profile // destructure profile object<font></font>數組
console.log(name) // "George"<font></font>url
console.log(hobby) // "Tennis"對象
這裏我用解構快速提取name和 hobby該屬性profile的對象。ip
使用別名,您能夠使用不一樣的變量名稱與相應的對象屬性相比,您從如下位置提取值:it
var profile = {name:'George', age:39, hobby:'Tennis'}<font></font>io
var {name:n, hobby:h} = profile // destructure profile object<font></font>console
console.log(n) // "George"<font></font>變量
console.log(h) // "Tennis"
嵌套對象解構
解構也適用於嵌套對象,我老是使用它來快速解決來自複雜JSON請求的值:
var jsondata = {<font></font>
title: 'Top 5 JavaScript ES6 Features',<font></font>
Details: {<font></font>
date: {<font></font>
created: '2017/09/19',<font></font>
modified: '2017/09/20',<font></font>
},<font></font>
Category: 'JavaScript',<font></font>
},<font></font>
url: '/top-5-es6-features/'<font></font>
};<font></font>
<font></font>
var {title, Details: {date: {created, modified}}} = jsondata<font></font>
console.log(title) // 'Top 5 JavaScript ES6 Features'<font></font>
console.log(created) // '2017/09/19'<font></font>
console.log(modified) // '2017/09/20'