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](https://miro.medium.com/max/9999/1*xysCGyrM8MFSOYOemc97JA.png)
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](https://miro.medium.com/max/9999/1*BvyUlK6lIGd-V_Ha3UFGxQ.png)
We can also do this with the same result,
我们也可以达到相同的结果
![Image for post](https://miro.medium.com/max/9999/1*oJ63z6DN7llvh6JN76ANGA.png)
we can also declare variables before Assignment,
我们也可以在赋值之前声明变量,
![Image for post](https://miro.medium.com/max/9999/1*xsavDDBIoJhGpGTxA0IcKQ.png)
Assign variables a default value:
为变量分配一个默认值:
![Image for post](https://miro.medium.com/max/9999/1*PURVhPpbVSZ_L2WjxpcMPA.png)
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](https://miro.medium.com/max/9999/1*OMO8fVdTU_3rFLj8DIjZmg.png)
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](https://miro.medium.com/max/9999/1*S3h8WAWfU07XxVcfPsmBJQ.png)
Rest(…) operator:
Rest(…)运算符:
![Image for post](https://miro.medium.com/max/9999/1*XVaeyMuXnFsr2lbUH525Fg.png)
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](https://miro.medium.com/max/9999/1*Rl-0QiIidkDjWqroPIfyfw.png)
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