第五章 解构:使数据访问更便捷node
对象解构数组
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的值rest
let {type, name, value = '123'} = node;
嵌套对象解构code
将对象拆解以获取你想要的信息。对象
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];
不定元素co
数组的解构能够使用扩展运算符...来分拆或组合数组。
let [first, ...rest] = colors; // rest = ['green', 'blue'] let mixed = [...colors, ...rest]; // mixed = ['red', 'green', 'blue', 'green', 'blue']
解构参数
在函数的参数表中,能够直接将某个参数对象的属性经过解构的方式得到,从而在函数中做为变量使用。
解构参数建议提供被解构对象的默认值{},从而避免从undefined中去解构,产生报错。
解构时,能够为每一个解构的属性提供默认值。