简体   繁体   English

在破坏嵌套数组时为变量分配默认值

[英]Assigning default value to variable in destructing nested array

I am wondering how to assign default values when destructing a nested array.我想知道如何在破坏嵌套数组时分配默认值。 I have myArr array which has a nested array [12, 25, 1, 6]我有myArr数组,它有一个嵌套数组[12, 25, 1, 6]


let  myArr = [11, 100,  33,  [12, 25, 1, 6], 77]

I want to assign a default value to four when destructing myArr as below我想在销毁myArr时将默认值分配给four ,如下所示


const[ one = 999, two = 999, three = 999, four = [ ], five = 999]  = myArr

And I also want to destructure elements of the nested array.而且我还想解构嵌套数组的元素。

const[ one = 999, two = 999, three = 999, [innerOne = 1, ...rest ], five = 999]  = myArr

Is it possible to assign a default value to variable four and destructure the elements of the nested array [12, 25, 1, 6] concurrently in one line?是否可以为变量four分配一个默认值并在一行中同时解构嵌套数组[12, 25, 1, 6]的元素?

You can do this by destructuring the array as an object.您可以通过将数组解构为对象来实现此目的。 When destructuring an object, you can assign aliases, and destructure a property more than once (index 3 in this case).解构对象时,您可以分配别名,并多次解构属性(在本例中为索引 3)。

 const myArr = [11, 100, 33, [12, 25, 1, 6], 77] const { 0: one = 999, 1: two = 999, 2: three = 999, 3: four = [], 3: [innerOne = 1, ...rest ], 4: five = 999 } = myArr console.log(one, two, three, four, innerOne, rest, five)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM