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

Assigning default value to variable in destructing nested array

我想知道在销毁嵌套数组时如何分配默认值。 我有 myArr 数组,其中有一个嵌套数组 [12, 25, 1, 6]


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

我想在销毁 myArr 时为 four 分配一个默认值,如下所示


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

而且我还想解构嵌套数组的元素。

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

是否可以在一行中同时为变量 four 分配默认值并解构嵌套数组 [12, 25, 1, 6] 的元素?

您可以通过将数组解构为对象来完成此操作。解构对象时,您可以分配别名,并多次解构 属性(在本例中为索引 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)