这种写法属于“模式匹配”,只要等号两边的模式相同,左边的变量就会被赋予对应的值。下面是一些使用嵌套数组进行解构的例子。
如果解构不成功,变量的值就等于undefined。
let[foo,[[bar],baz]]=[1,[[2],3]];
运行结果:
foo //1
bar //2
baz// 3
let [,,third]=["foo","bar","baz"];
运行结果:
third // "baz";
let[x,,y]=[1,2,3];
运行结果:
x// 1;
y// 3;
let[head,...tail]=[1,2,3,4];
运行结果:
head // 1;
tail // [2, 3, 4];
let[x,y,...z]=['a'];
运行结果:
x // "a";
y // undefined;
z // [];