设为首页 加入收藏

TOP

ES6 解构
2019-09-17 18:26:04 】 浏览:14
Tags:ES6 解构

第五章 解构:使数据访问更便捷

对象解构

let node = {
  type: 'id',
  name: 'foo',
};

let {type, name} = node; // type === 'id', name === 'foo'
let {type: TYPE, name: NAME} = node; // TYPE === 'id', NAME === 'node'

默认值

可以在结构语句中添加默认值,使其覆盖false like的值

let {type, name, value = '123'} = node;

嵌套对象解构

将对象拆解以获取你想要的信息。

let {loc: {start}} = node; // 从node中提取node.loc.start,赋值给start

数组解构

使用数组字面量,且解构操作全部在数组内完成。

let colors = ['red', 'greed', 'blue'];

let [first, second] = colors; // first === 'red', second === 'green'
let [, , third] = colors; // third === 'blue'
let [, , , fourth = 'black'] = colors // 使用默认值,fourth === 'black'

数组的解构可以用来交换变量

let a = 1, b = 2;
[b, a] = [a, b];

不定元素

数组的解构可以使用扩展运算符...来分拆或组合数组。

let [first, ...rest] = colors; // rest = ['green', 'blue']
let mixed = [...colors, ...rest]; // mixed = ['red', 'green', 'blue', 'green', 'blue']

解构参数

在函数的参数表中,可以直接将某个参数对象的属性通过解构的方式获得,从而在函数中作为变量使用。

解构参数建议提供被解构对象的默认值{},从而避免从undefined中去解构,产生报错。

解构时,可以为每个解构的属性提供默认值。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇js获取客户端IP 下一篇js对象常用属性和方法:复制一个..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目