数组的解构

与对象解构的语法相比,数组解构就简单多了,它使用的是数组字面量,且解构操作全部在数组内完成,而不是像对象字面量语法一样使用对象的命名属性。

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’。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

codereasy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值