zoukankan      html  css  js  c++  java
  • ES6 学习笔记

    变量的解构赋值


    学习资料:ECMAScript 6 入门

    数组的解构赋值

    基本用法

    可以从数组中提取值,按照对应位置,对变量赋值。这种写法属于“模式匹配”。

    let [a, b, c] = [1, 2, 3];
    
    let [head, ...tail] = [1, 2, 3, 4];
    head // 1
    tail // [2, 3, 4]
    
    let [x, y, ...z] = ['a'];
    x // "a"
    y // undefined
    z // []
    

    如果等号的右边不是数组(或者严格地说,不是可遍历的结构),那么将会报错。

    // 报错 前五个表达式转为对象以后不具备 Iterator 接口  最后一个本身不具备 Iterator 接口
    let [foo] = 1;
    let [foo] = false;
    let [foo] = NaN;
    let [foo] = undefined;
    let [foo] = null;
    let [foo] = {};
    

    只要某种数据结构具有 Iterator 接口,都可以采用数组形式的解构赋值。

    function* fibs() {
        let a = 0;
        let b = 1;
        while (true) {
            yield a;
            [a, b] = [b, a + b];
        }
    }
    
    let [first, second, third, fourth, fifth, sixth] = fibs();
    console.log(first, second, third, fourth, fifth, sixth); // 0 1 1 2 3 5
    

    默认值

    如果一个数组成员不严格等于undefined,默认值是不会生效的。

    let [foo = true] = []; // foo=true
    let [x, y = 'b'] = ['a']; // x='a', y='b'
    let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
    let [x = 1] = [null]; // x=null
    

    默认值可以引用解构赋值的其他变量,但该变量必须已经声明。

    let [x = 1, y = x] = [];     // x=1; y=1
    let [x = 1, y = x] = [2];    // x=2; y=2
    let [x = 1, y = x] = [1, 2]; // x=1; y=2
    let [x = y, y = 1] = [];     // ReferenceError
    

    对象的解构赋值

    let { foo, bar } = { foo: "aaa", bar: "bbb" };
    foo // "aaa"
    bar // "bbb"
    

    如果变量名与属性名不一致,必须写成下面这样。

    let obj = { first: 'hello', last: 'world' };
    let { first: f, last: l } = obj;
    f // 'hello'
    l // 'world'
    

    对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。

    let { foo: baz } = { foo: "aaa", bar: "bbb" };
    baz // "aaa"
    foo // error: foo is not defined
    

    如果p也要作为变量赋值,可以写成下面这样。

    let obj = {
    p: [
        'Hello',
        { y: 'World' }
    ]
    };
    
    let { p, p: [x, { y }] } = obj;
    x // "Hello"
    y // "World"
    p // ["Hello", {y: "World"}]
    

    嵌套赋值:

    let obj = {};
    let arr = [];
    
    ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true });
    
    obj // {prop:123}
    arr // [true]
    

    如果解构模式是嵌套的对象,而且子对象所在的父属性不存在,那么将会报错。

    // 报错
    let {foo: {bar}} = {baz: 'baz'};
    

    以下的例子,JavaScript 引擎会将{x}理解成一个代码块,从而发生语法错误。

    // 错误的写法
    let x;
    {x} = {x: 1};
    // SyntaxError: syntax error
    
    // 正确的写法
    let x;
    ({x} = {x: 1});
    

    对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。

    let { log, sin, cos } = Math;
    

    数组本质是特殊的对象,因此可以对数组进行对象属性的解构。

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

    字符串的解构赋值

    let {length : len} = 'hello';
    len // 5
    

    数值和布尔值的解构赋值

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

    let {toString: s} = 123;
    s === Number.prototype.toString // true
    
    let {toString: s} = true;
    s === Boolean.prototype.toString // true
    

    由于undefined和null无法转为对象,所以对它们进行解构赋值,都会报错。

    let { prop: x } = undefined; // TypeError
    let { prop: y } = null; // TypeError
    

    函数参数的解构赋值

    [[1, 2], [3, 4]].map(([a, b]) => a + b); // [ 3, 7 ]
    

    函数参数的解构也可以使用默认值。

    function move({x = 0, y = 0} = {}) {
         return [x, y];
    }
    
    move({x: 3, y: 8}); // [3, 8]
    move({x: 3}); // [3, 0]
    move({}); // [0, 0]
    move(); // [0, 0]
    

    下面代码为函数move的参数指定默认值,而不是为变量x和y指定默认值,所以会得到与前一种写法不同的结果。

    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]
    

    undefined就会触发函数参数的默认值。

    [1, undefined, 3].map((x = 'yes') => x);
    // [ 1, 'yes', 3 ]
    

    圆括号问题

    只要有可能,就不要在模式中放置圆括号。

    不能使用圆括号的情况:

    • 变量声明语句

        // 全部报错
        let [(a)] = [1];
      
        let {x: (c)} = {};
        let ({x: c}) = {};
        let {(x: c)} = {};
        let {(x): c} = {};
      
        let { o: ({ p: p }) } = { o: { p: 2 } };
      
    • 函数参数

        // 报错
        function f([(z)]) { return z; }
        // 报错
        function f([z,(x)]) { return x; }
      
    • 赋值语句的模式

        // 全部报错
        ({ p: a }) = { p: 42 };
        ([a]) = [5];
        [({ p: a }), { x: c }] = [{}, {}];
      

    可以使用圆括号的情况只有一种:赋值语句的非模式部分,可以使用圆括号。

    [(b)] = [3]; // 正确
    ({ p: (d) } = {}); // 正确
    [(parseInt.prop)] = [3]; // 正确
    

    上面三行语句都可以正确执行,因为首先它们都是赋值语句,而不是声明语句;其次它们的圆括号都不属于模式的一部分。第一行语句中,模式是取数组的第一个成员,跟圆括号无关;第二行语句中,模式是p,而不是d;第三行语句与第一行语句的性质一致。

    用途

    • 交换变量的值

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

        // 返回一个数组
      
        function example() {
            return [1, 2, 3];
        }
        let [a, b, c] = example();
      
        // 返回一个对象
      
        function example() {
            return {
                foo: 1,
                bar: 2
            };
        }
        let { foo, bar } = example();
      
    • 函数参数的定义

    解构赋值可以方便地将一组参数与变量名对应起来。

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

        let jsonData = {
            id: 42,
            status: "OK",
            data: [867, 5309]
        };
      
        let { id, status, data: number } = jsonData;
      
        console.log(id, status, number);
        // 42, "OK", [867, 5309]
      
    • 函数参数的默认值

    指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句。

        jQuery.ajax = function (url, {
            async = true,
            beforeSend = function () {},
            cache = true,
            complete = function () {},
            crossDomain = false,
            global = true,
            // ... more config
            }) {
            // ... do stuff
        };
    
    • 遍历Map结构

    Map结构原生支持Iterator接口,配合变量的解构赋值,获取键名和键值就非常方便。

        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
    
    • 输入模块的指定方法

    加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰。

    const { SourceMapConsumer, SourceNode } = require("source-map");
    
  • 相关阅读:
    hello word
    HDU 1006 Tick and Tick
    HDU 1005 Number Sequence
    HDU 1004 Let the Balloon Rise
    HDU 1003 Max Sum
    HDU 1002 A + B Problem II
    HDU 1001 Sum Problem
    HDU 1000 A + B Problem
    POJ 2253 Frogger
    POJ 2387 Til the Cows Come Home
  • 原文地址:https://www.cnblogs.com/renleimlj/p/7773188.html
Copyright © 2011-2022 走看看