JS解构赋值

1、交换变量

通常使用交换变量是定义一个临时变量然后进行交换,而使用解构赋值就能快速的交换变量,例如

// 常用方法
let temp;
let a;
let b;
temp = a;
a = b;
b = temp

//使用解构赋值
let a = 1;
let b = 2;

[a, b] = [b, a];

a; // => 2
b; // => 1

2、访问数组中的元素

有种场景,咱们可能有一个为空的项数组。并且希望访问数组的第一个、第二个或第n个项,但如果该项不存在,则使用指定默认值。

通常会使用数组的length属性来判断

const colors = [];

let firstColor = 'white';
if (colors.length > 0) {
 firstColor = colors[0];
}

firstColor; // => 'white'

使用数组解构,可以更简洁的实现同样的效果:

const colors = [];

const [firstColor = 'white'] = colors;

firstColor; // => 'white'

const [firstColor = ‘white’] = colors 解构将colors数组的第一个元素赋给firstColor变量。如果数组在索引0处没有任何元素,则分配“white”默认值。

当然还可以更灵活,如果只想访问第二个元素,可以这么做。

const colors = [];

const [, secondColor = 'black'] = colors;

secondColor; // => 'black'

注意解构左侧的逗号:它表示忽略第一个元素,secondColor使用colors数组中索引为1的元素进行赋值。

3、解构动态属性

let jsonData = {
	a:1,
	b:2
	}
const {a, b} = jsonData;
a; // 1
b; // 2

4、解构 iterables

许多原生基本类型和对象都是可迭代的: array, string, typed arrays, set 和 map。
如果不想局限于基本类型,通过实现可迭代协议,可以定制解构逻辑。
movies包含一个movie对象列表。在解构movies时,将title作为字符串获取是非常棒的。让咱们实现一个自定义迭代器。

const movies = {
  list: [
    { title: 'Heat' }, 
    { title: 'Interstellar' }
  ],
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.list.length) {
          const value = this.list[index++].title;
          return { value, done: false };
        }
        return { done: true };
      }
    };
  }
};

const [firstMovieTitle] = movies;
console.log(firstMovieTitle); // => 'Heat'

movies对象通过定义Symbol.iterator方法来实现可迭代协议,迭代器迭代title。

遵循iterable协议允许将movies对象分解为title,具体方法是读取第一个movies的title:const [firstMovieTitle] = movies。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值