一.数组的解构赋值

  1.举几个例子足以理解

  1. let [a, b, c] = [1, 2, 3]; a:1;  b:2;  c:3;

  2. let [x, , y] = [1, 2, 3];  x:1   y:2;

  3. let [foo, [[bar], baz]] = [1, [[2], 3]]; foo:1; bar:2; baz:3;

  4. let [head, ...tail] = [1, 2, 3, 4];head:1;  tail:[2,3,4];

  5. let [a, [b], d] = [1, [2, 3], 4];a:1  b:2  d:4;

二.对象的解构赋值

  1.举几个例子足以理解

    1. let { a, b} = { a: "aaa", b: "bbb" };a:"aaa"  b:"bbb";

    2. let { c } = { a: "aaa", b: "bbb" };c:undefined;

    3. let obj = { p: [ 'Hello', { y: 'World' } ] }; let { p: [x, { y }] } = obj;x:'hello' y:'world';

    4. const node = { loc: { start: { line: 1, column: 5 } } }; let { loc, loc: { start }, loc: { start: { line }} } = node; line // 1 loc // Object {start: Object} start // Object {line: 1, column: 5}

    5. var { message: msg = 'Something went wrong' } = {}; msg // "Something went wrong"(对象的解构赋值也可以设置默认值);默认值生效的条件:对象的属性值严格等于undefined

    6. var {x = 3} = {x: null}; x // null;null 不严格的等于undefined;

    7. // 报错  let {foo: {bar}} = {baz: 'baz'}; foo的值等于undefined;undefined没有bar属性;

    8. // 错误的写法 let x; {x} = {x: 1}; // SyntaxError: syntax error;对于已经声明的值进行解构赋值的时候要格外小心;正确写法({x} = {x: 1});不加小括号的时候,{x}是一个独立的代码块;

    9. 常用的场景:let { log, sin, cos } = Math;

    10. let arr = [1, 2, 3]; let {0 : first, [arr.length - 1] : last} = arr; first // 1 last // 3

三.字符串的解构赋值

  1.仍然举几个例子说事情:

    1. const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o";

    2. let {length : len} = 'hello'; len // 5; 因为'hello'也有length属性,所以,len==5;

四.数值和布尔值的解构赋值

  1.解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。

    1. let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true;;;;上面代码中,数值和布尔值的包装对象都有toString属性,因此变量s都能取到值。
    2. let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError;;;解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefinednull无法转为对象,所以对它们进行解构赋值,都会报错。

五.函数参数的解构赋值

  1.function add([x, y]){ return x + y; } add([1, 2]); // 3

  2.function move({x, y} = { x: 0, y: 0 }) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, undefined] move({}); // [undefined, undefined] move(); // [0, 0];带有默认值的函数;

五.函数参数的解构赋值

  1.圆括号的问题:ES6 的规则是,只要有可能导致解构的歧义,就不得使用圆括号。下列情况均会报错:

    1. 变量的声明不可以使用圆括号;
    2. 函数参数不允许使用圆括号;
    3. 复制语句模式不可以使用圆括号;          

ES6的文档下面还有部分内容,如果感兴趣可以自己再去浏览:变量的解构赋值;

 
05-11 22:37