avaScript ES6值得掌握的五大功能(4)JavaScript解构
在Arrow Functions旁边,这是我每天使用最多的ES6功能。ES6 Destructuring不是一个新功能,而是一种新的赋值语法,它允许您快速从对象属性和数组中解压缩值并将它们分配给单个变量。
1
2
3
4
var
profile = {name:
'George'
, age:39, hobby:
'Tennis'
}<font></font>
var
{name, hobby} = profile
// destructure profile object<font></font>
console.log(name)
// "George"<font></font>
console.log(hobby)
// "Tennis"
这里我用解构快速提取name
和hobby
该属性profile
的对象。
使用别名,您可以使用不同的变量名称与相应的对象属性相比,您从以下位置提取值:
1
2
3
4
var
profile = {name:
'George'
, age:39, hobby:
'Tennis'
}<font></font>
var
{name:n, hobby:h} = profile
// destructure profile object<font></font>
console.log(n)
// "George"<font></font>
console.log(h)
// "Tennis"
解构也适用于嵌套对象,我总是使用它来快速解决来自复杂JSON请求的值:
1
2
3
4
五
6
7
8
9
10
11
12
13
14
15
16
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'
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。