ES6 解構

第五章 解構:使數據訪問更便捷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中去解構,產生報錯。

解構時,能夠爲每一個解構的屬性提供默認值。

相關文章
相關標籤/搜索