const colors = ['red', 'green', 'blue', 'orange', [ 'black', 'white' ] ];
// 1. 使用数组解构初始化变量
// 数组中的元素会按照顺序赋值给这 3 个变量
let [ firstColor, secondColor, thirdColor ] = colors;
console.log(firstColor, secondColor, thirdColor)
// 2. 使用数组解构为变量重新赋值
let firstColor = 'black', secondColor = 'white';
// 数组中的元素会按照顺序赋值给这 2 个变量
[ firstColor, secondColor ] = colors;
console.log(firstColor, secondColor)
// 3. 为变量指定默认值
// 当数组中没有第 4 个元素时,变量 fourthColor 会被赋值成默认值 'pink'
let [ firstColor, secondColor, thirdColor, fourthColor = 'pink' ] = colors;
console.log(firstColor, secondColor, thirdColor, fourthColor)
// 4. 跳过数组中的指定元素
let [ firstColor, , ,fourthColor ] = colors;
console.log(firstColor, fourthColor)
// 5. 嵌套数组解构
let [,,,,[nestedFirstColor, nestedSecondColor]] = colors;
console.log(nestedFirstColor, nestedSecondColor)
ES6-数组解构
最新推荐文章于 2022-09-15 08:51:15 发布