JavaScript中的对象分解

Destructuring is a convenient way of extracting multiple values from data stored in objects and Arrays. ES6 introduced some significant improvements to the language, including the de-structuring of Objects and Arrays. Honestly speaking, these are my favorite edition in the JavaScript standard syntax.

d estructuring是从存储在对象和数组数据提取的多个值的一种方便的方法。 ES6对该语言进行了一些重大改进,包括对对象和数组的解构。 老实说,这是我最喜欢JavaScript标准语法版本。

对象解构 (Object destructuring)

Object destructuring takes a similar tack as array destructuring. Suppose you have a student object with two properties: name and id. Previously in javascript, when you want to assign the variables to the properties of the student object, you need to make a variable from something that is inside of an object like this:

对象解构与数组解构相似。 假设您有一个带有两个属性的Student对象:name和id。 以前在javascript中,当您想将变量分配给Student对象的属性时,需要从对象内部的内容中创建一个变量,如下所示:

Image for post

Here, you’ve got this pretty much repetitive code over and over again. But ES6 destructuring assignment makes it easier and single line like this:

在这里,您将一遍又一遍地得到这段重复的代码。 但是,ES6的解构分配使它变得更容易且像这样:

Image for post

Assignment without declaration:

没有声明的分配:

A variable can be assigned its value with destructuring separate from its declaration.

变量可以通过与声明分开的方式分配其值。

Image for post

Assigning to new variable names:

分配给新的变量名称:

We can be assigned to a variable with a different name than the object property.

我们可以分配给一个名称与对象属性不同的变量。

Image for post

Default values:

默认值:

It is possible to set default values when using the destructuring assignment.

使用解构分配时可以设置默认值。

Image for post

Here, const creates variables, so id is undefined. But we can fix this problem using the default value.

在这里,const创建变量,所以id是不确定的。 但是我们可以使用默认值解决此问题。

Image for post

Note: Default values in destructuring can’t working with null, false, and 0. It only works if the variables either don’t exist or their value is set to undefine.

注意:解构中的默认值不能与null,false和0一起使用。仅在变量不存在或变量的值设置为undefine时才起作用。

Rest(…) operator in Object Destructuring:

对象解构中的Rest(…)运算符:

The Rest properties add the rest syntax to destructuring.

Rest属性将rest语法添加到解构中。

Image for post

I hope this lesson provides a clear understands of how Destructuring works in JavaScript. Hopefully, you learned something today. Happy Coding.

我希望本课能使您清楚地了解Destructuring如何在JavaScript中工作。 希望您今天学到了一些东西。 编码愉快。

翻译自: https://medium.com/swlh/object-destructuring-in-javascript-c905fc676501

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值