# 对象解构

# 解构

let node = {
  type: "Identifier",
  name: "foo"
};

let { type, name, value} = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // undefined

# 解构时设置默认值,如果值为undefined

let node = {
  type: "Identifier",
  name: "foo"
};

let { type, name, value = true} = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // true

# 为非同名局部变量赋值

let node = {
  type: "Identifier",
  name: "foo"
};
// 冒号前的标识符代表在对象中检索位置
// 冒号后才是赋值的变量名
let { type: localType, name: localName, value:localValue = true} = node;
console.log(localType); // "Identifier"
console.log(localName); // "foo"
console.log(localValue); // true

# 嵌套对象解构

let node = {
  type: "Identifier",
  name: "foo",
  loc: {
    start: {
      line: 1,
      column: 1
    }
  }
};
// 冒号前的标识符代表在对象中检索位置
// 冒号后才是赋值的变量名
let { loc: { start } } = node;
console.log(start.line); // 1

let { loc: { start: localStart } } = node;
console.log(localStart.line); // 1

# 不定元素

  1. 只能放在最后
  2. 只能浅复制
let colors = {a:1, b:2,c:3};
let {a, ...rest} = colors;
console.log(rest) // {b:2, c:3}
let colors = [{color: 'red'}];
let [...clonedColor] = colors;
clonedColor[0].color = 'green';
console.log(colors[0].color) // 'green'

# 数组解构

# 解构

let colors = ['red', 'green', 'blue'];
let [firstColor] = colors;
console.log(firstColor) // 'red'

# 交换变量

let a = 1, b = 2;
[a, b] = [b, a];
console.log(a) // 2
console.log(b) // 1

# 取某个值

let colors = ['red', 'green', 'blue'];
let [ , , thirdColor] = colors;
console.log(thirdColor) // 'blue'

# 默认值

let colors = ['red'];
let [firstColor, secondColor = 'green'] = colors;
console.log(secondColor) // 'green'

# 嵌套

let colors = ['red', ['green', 'blue']];
let [firstColor, [secondColor] ] = colors;
console.log(secondColor) // 'green'

# 不定元素

  1. 只能放在最后
  2. 只能浅复制数组
let colors = ['red', 'green', 'blue'];
let [firstColor, ...restColors] = colors;
console.log(restColors) // ['green', 'blue']
let colors = [{color: 'red'}];
let [...clonedColor] = colors;
clonedColor[0].color = 'green';
console.log(colors[0].color) // 'green'

# 混合解构

应用,从JOSN对象提取信息

let node = {
  loc: {
    line: 1
  },
  range: [0, 3] 
};
let {loc: start, range: [startIndex]} = node;
console.log(start.line) // 1
console.log(startIndex) // 0

# 解构参数

# 代替 可选options

// es5
function setCookie(name, value, options) {
  options = options || {};  
  let secure = options.secure,
      path = options.path; 
}

// es6
function setCookie(name, value, {secure, path} = {}) {
  
}

# 参数默认值

let defaultState = {
  secure: true,
  path: 'example.com'
};

function setCookie(name, value, {secure, path} = defaultState) {
  
}