The deconstruction of an array is a simple syntax that assigns the cell values of the array to some column variables in a quick and batch manner
Basic syntax:
1.赋值运算符 = 左侧的 [] 用于批量生成变量,右侧数组的单元值将被赋值给左侧的变量
2. The order of the variables corresponds to the position of the array unit value for assignment
const [max,avg,min]=[100,80,60] console.log(max,avg,min)
Exchange two variable values
let a=1 let b=2; [b,a]=[a,b] console.log(a,b)
In the case of multiple variables with few values, the redundant variable values are undefined
const [c,d,e,f]=[1,2,3] console.log(c) console.log(d) console.log(e) console.log(f)//f的值为undefined
If there are few variables and many cell values, you can use deconstruction assignment to assign the redundant cell values to the array
const [g,h,...i]=[1,2,3,4,5] console.log(g) console.log(h) console.log(i)//i=[3,4,5]
To prevent undefined transfer of unit values, you can set the default value
const [j='手机',k='电脑']=['bb机'] console.log(j)//j='bb机' console.log(k)//k='电脑'
Import and assign values as required, ignore them, but leave the position
const [l,,m,n]=[1,2,3,4] console.log(l)//l=1 console.log(m)//m=3 console.log(n)//n=4
Multidimensional array deconstruction
const [p,q,[r,s]]=[1,2,[3,4]] console.log(p)//p=1 console.log(q)//q=2 console.log(r)//r=3 console.log(s)//s=4