我想知道在破坏嵌套数组时如何分配默认值。我有myArr
数组,其中有一个嵌套数组[12, 25, 1, 6]
let myArr = [11, 100, 33, [12, 25, 1, 6], 77]
如下破坏four
时,我想为myArr
指定默认值
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)