与对象解构的语法相比,数组解构就简单多了,它使用的是数组字面量,且解构操作全部在数组内完成,而不是像对象字面量语法一样使用对象的命名属性。
let list = ['a','b','c'];
let [first,second] = list;
console.log(first,second);
在上面的代码中,我们从数组 list 中解构出数组索引 0 和 1 所对应的值并分别存储至变量 first 和 second 中。
在数组的解构中,也可以直接省略元素,只为需要的元素提供变量名:
let list = ['a','b','c'];
let [first,,third] = list;
console.log(first,third);
这段代码中使用解构语法从数组 list 中获取索引 0 和索引 2 所对应的元素,
默认值
在数组的解构赋值表达式中也可以为数组的任意位置添加默认值,当指定位置的属性不存在或其值为 undefined 时使用默认值:
let list = ['a','b'];
let [first,second,third = '我是默认值'] = list;
console.log(first,second,third);
嵌套数组的解构赋值
就像对象一样,也可以对嵌套数组进行解构操作,在原有的数组解构模式中插入另一个数组解构模式,即可将解构过程深入到下一级:
let colors = [ 'red' , [ 'green' , 'yellow' ] , 'blue' ];
let [ firstColor , [ secondColor ] ] = colors;
console.log(firstColor,secondColor); // red , green
在这个例子中,我们通过数组的嵌套解构,为变量 firstColor 和 secondColor 分配对应的值。
如果想解构出来’yellow,
let colors = ["red", ["green", "yellow"], "blue"];
let [firstColor, [, secondColor]] = colors;
console.log(firstColor, secondColor); // red , yellow
不定元素
在数组中,可以通过…语法将数组中的其余元素赋值给一个特定的变量,就像这样:
let colors = ['red','green','blue'];
let [firstColor,...otherColors] = colors;
console.log(firstColor); // red
console.log(otherColors); // ['green','blue']
这个例子中,数组 colors 的第一个元素被赋值给了 firstColor ,其他元素被赋值给了 otherColors 数组,所以 otherColors 中包含两个元素:‘green’ 和 ‘blue’。