ES6系列文章 Destructuring

Destructuring解构是ES6很重要的一个部分。和箭头函数、letconst 同等地位,解构可能是你日常用到最多的语法之一了。解构是什么意思呢?它是js 表达式,允许我们从数组、对象、map、set 中抽取数据同时为多个变量赋值。

解构入门

首先让我们初步了解下解构解决哪些问题。你可能从后台得到 person 的数据如下:

const person = {
    first: 'xi',
    last: 'xi',
    country: 'china',
    city: 'beijing'
};
// 需要单独获得 first和 last 的值
const first = person.first;
const last = person.last;

想从 person 对象中获取到数据不得不写大量重复的代码。此时解构的价值就体现出来了。解构代码如下:

const { first, last } = person;

上面的代码表示声明两个变量 first last,然后 first = person.first, last = person.last。如果你还行获取 person的 city,只需进行如下操作:

const { first, last, city } = person;

以上: 解构可以减少重复的代码

解构之重命名

有时后台返回的命名比较狗血,你不喜欢或者变量名在该作用域中已经被占用了。例如:

const country = 'USA';
const person = {
    first: 'xi',
    last: 'xi',
    country: 'china',
    city: 'beijing'
};
const {first, last, country?} = person;

此时你仍想获取 person 中的 coutry 数据怎么办呢?为此解构重命名功能就闪亮登场。

// personCountry is whart you needs
const {first, last, country: personCountry} = person;

解构之设置默认值

ES6为我们提供了设置默认值的语法。解构也一样。下面大家思考一下,在对一个 object 进行解构时,若对应的对象属性不存在那会怎样呢?

const rect = {
    width: 150
}
const { height, width } = rect;
console.log(height);//undefined

运行代码我们看到 height === undefined。实际业务中长方形的 height 是不能没有值的。为了增强程序的健壮性,我们经常会给 height 一个默认值。height || 150。下面介绍解构设置默认值的语法

const rect = {
    width: 150
}
const { height = 150, width = 300 } = rect;
console.log(height, width);//150, 150

?在解构设置默认值的语法中, 我们要特别注意只有当 value 的值严格等于 undefined 时,默认值才会生效。null, false, 0都算正常值的范畴。

解构进阶

解构时同时使用重命名和设置默认值的语法。直接上代码:

const person = { first: 'xi', last: 'yuanyuan' };
const { middle: middleName = 'xixi' } = person;
console.log(middleName); // 'xixi'

若可以理解上面的代码,那你的 es6水平已经很好了。下面对上述语句做简单说明:

  1. 首先我们声明了一个变量middleName
  2. 其次我们查询 person的 middle 属性,看其是否有值。若有,middleName = person.middle
  3. 若 person 没有 middle 属性, 那么将middleName赋值为'xixi'。

refs

JavaScript’s Destructuring

欢迎访问个人博客 ?xixi小站?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值