温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

avaScript ES6值得掌握的五大功能(4)JavaScript解构

发布时间:2020-08-09 13:18:22 来源:ITPUB博客 阅读:128 作者:cenfeng 栏目:web开发

在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'


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI