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标准语法版本。

阵列解构 (Array destructuring)

Let us take a look if we want to extract data from an array in es5.

让我们看一下是否要从es5中的数组中提取数据。

Image for post

Here, we are doing something quite boring stuff and repeated the same thing again and again. But ES6 destructuring assignment makes it easier.

在这里,我们正在做一些非常无聊的事情,并一次又一次地重复同样的事情。 但是,通过ES6进行销毁分配会更加容易。

Image for post

We can also do this with the same result,

我们也可以达到相同的结果

Image for post

we can also declare variables before Assignment,

我们也可以在赋值之前声明变量,

Image for post

Assign variables a default value:

为变量分配一个默认值:

Image for post

Here, you can see that we didn’t assign value for num3 and the console gives no error or undefine message because it takes its default value, and print it.

在这里,您可以看到我们没有为num3分配值,并且控制台没有给出错误或未定义消息,因为它采用了默认值并打印出来。

Swapping Values:

交换值:

Did you know that two variable values can be swapped in one destructuring assignment? Let’s take an example,

您是否知道可以在一个解构分配中交换两个变量值? 让我们举个例子

Image for post

Skipping Items in an Array:

跳过数组中的项目:

If you want to Skipping Items in an Array, you can also do this by array destructuring. Simply use a comma operator to skip an item on an array.

如果要跳过数组中的项目,也可以通过数组解构来执行此操作。 只需使用逗号运算符即可跳过数组中的项目。

Image for post

Rest(…) operator:

Rest(…)运算符:

Image for post

Here, num1 is assigned for 1 and the rest of the items on this array are assigned on the particular variable num2.

此处,num1分配给1,而此数组上的其余项目分配给特定变量num2。

Destructuring with Functions:

功能分解:

You can extract data from an array returned from a function. Have a look the example below,

您可以从函数返回的数组中提取数据。 看下面的例子,

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/array-destructuring-in-javascript-141196434d65

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值