简介

  1. 基本用法: let [a, b, c] = [1, 2, 3]
  2. 默认值:let [ n = 1] = []
  3. 解构不成功,变量的值等于undefined

对象的解构赋值

  1. 基本用法:let {foo, bar} = {foo: 'aaa', bar: 'bbb'}
  2. 默认值:let {x = 3} = {x: undefined}
  3. 默认值生效的条件是对象的属性值严格等于undefined

字符串的解构赋值

  1. 基本用法:cosnt [a, b, c, d, e] = 'hello' //a = ‘h’, b = ‘e’

用途:

  1. 交换变量的值:

    1
    2
    3
    let x = 1;
    let y = 2;
    [x, y ] = [y, x]
  2. 从函数返回多个值:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 返回一个数组

    function example() {
    return [1, 2, 3];
    }
    let [a, b, c] = example();

    // 返回一个对象

    function example() {
    return {
    foo: 1,
    bar: 2
    };
    }
    let { foo, bar } = example();
  3. 定义函数参数:

    1
    2
    3
    4
    5
    6
    7
    // 参数是一组有次序的值
    function f([x, y, z]) { ... }
    f([1, 2, 3]);

    // 参数是一组无次序的值
    function f({x, y, z}) { ... }
    f({z: 3, y: 2, x: 1});
  4. 提取JSON数据:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    let jsonData = {
    id: 42,
    status: "OK",
    data: [867, 5309]
    };

    let { id, status, data: number } = jsonData;

    console.log(id, status, number);
    // 42, "OK", [867, 5309]
  5. 遍历map结构:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    const map = new Map();
    map.set('first', 'hello');
    map.set('second', 'world');

    for (let [key, value] of map) {
    console.log(key + " is " + value);
    }
    // first is hello
    // second is world