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]
let myArr = [11, 100, 33, [12, 25, 1, 6], 77]
I want to assign a default value to four
when destructing myArr
as below
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?
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).
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.