美文网首页
(二)解构赋值

(二)解构赋值

作者: 做最棒的 | 来源:发表于2018-08-23 11:20 被阅读0次

    第三章 变量结构赋值

    不要忘记初始化程序

    // 语法错误
    var { a, c };
    let { a, b };
    const { c,d }
    var [a, c]
    let [a, c]
    const [a, c]
    

    1、数组的解构赋值

    定义: ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构。
    只要等号两边的模式相同,左边的变量就会被赋予对应的值。
    1)位置对应
    let [a, b, c] = [1, 2, 3];
    
    let [foo, [[bar], baz]] = [1, [[2], 3]];
    foo // 1
    bar // 2
    baz // 3
    
    let [ , , third] = ["foo", "bar", "baz"];
    third // "baz"
    
    let [x, , y] = [1, 2, 3];
    x // 1
    y // 3
    
    let [head, ...tail] = [1, 2, 3, 4];
    head // 1
    tail // [2, 3, 4]
    
    let [x, y, ...z] = ['a'];
    x // "a"
    y // undefined
    z // []
    
    2)解构不成功,返回undefined
    let [foo] = [];
    let [bar, foo] = [1];
    
    3)不完全解构,即等号左边的模式,只匹配一部分的等号右边的数组
    let [x, y] = [1, 2, 3];
    x // 1
    y // 2
    
    let [a, [b], d] = [1, [2, 3], 4];
    a // 1
    b // 2
    d // 4
    // 上面两个例子,都属于不完全解构,但是可以成功。
    
    4)Set 结构,也可以使用数组的解构赋值
    let [x, y, z] = new Set(['a', 'b', 'c']);
    x // "a"
    
    5)数据结构具有 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();
    sixth // 5
    console.log(first, second, third, fourth, fifth, sixth);
    
    6)数组解构赋值默认值

    解构赋值允许指定默认值。

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

    注意,ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于 undefined ,默认值才会生效。

    let [x = 1] = [undefined];
    x // 1
    
    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: y is not defined
    

    2、对象的解构赋值

    1)变量名与属性名不一致
    let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
    baz // "aaa"
    
    let obj = { first: 'hello', last: 'world' };
    let { first: f, last: l } = obj;
    f // 'hello'
    l // 'world'
    

    为什么可以这样
    对象属相的简写方式如下

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

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

    let { foo: baz } = { foo: "aaa", bar: "bbb" };
    baz // "aaa"
    foo // error: foo is not defined
    
    2)对象的解构也可以指定默认值。
    const Obj = {
        id: 123,
        name: 'chen',
            sex: undefined
    }
    let {
        id,
        name,
        sex: 123
    } = Obj;
     
    console.log(id, name, sex);
    
    
    const Obj = {
        id: 123,
        name: 'chen',
    }
    let {
        id,
        name,
        sex: 123
    } = Obj;
     
    console.log(id, name, sex);
    

    为什么?

    var {x = 3} = {x: undefined};
    x // 3
    
    var {x = 3} = {x: null};
    x // null
    
    默认值生效的条件是,对象的属性值严格等于undefined。

    上面代码中,属性x等于null,因为null与undefined不严格相等,所以是个有效的赋值,导致默认值3不会生效。

    如果解构失败,变量的值等于undefined。

    let {foo} = {bar: 'baz'};
    foo // undefined
    
    3)已经声明的变量用于解构赋值
    // bad写法
    let x;
    {x} = {x: 1};
    // SyntaxError: syntax error
    

    上面代码的写法会报错,因为 JavaScript 引擎会将{x}理解成一个代码块,从而发生语法错误。只有不将大括号写在行首,避免 JavaScript 将其解释为代码块,才能解决这个问题。

    // good写法
    let x;
    ({x} = {x: 1});
    

    推荐写法

    // best写法
    let {x} = {x: 1};
    

    实例

    let node = {
        type:'grade',
        name: 'zhang'
    }, type = 'haha',name = 'lisi';
    
    ({type,name} = node);
    
    function func(value) {
        console.log(value === node);
        value.type ='nihao';
        value.name = 'shuaige';
    }
    func({type,name}=node);
    console.log(type,name);
    
    4)对象方法的解构赋值
    console.log(Math["max"](3,1,33,22));
    let { log, sin, cos } = Math;
    
    5)数组按照对象方法的解构赋值
    let arr = [1, 2, 3];
    let {0 : first, [arr.length - 1] : last} = arr;
    
    let {a, b, c, length} = [1, 2, 3];
    console.log(a, b, c,length);
    为什么?
    
     let {0:a, 1:b, 2:c, length} = [1, 2, 3];
    console.log(a, b, c,length);
    console.log(Object([1, 2, 3]).length);
    console.log(...Object([1, 2, 3]));
    
    const { Id, name,toString} = {Id:1,name:2}
    console.log(Id, name,toString);
    

    为什么可以这样?

    4)嵌套解构赋值
    let obj = {
      p: [
        'Hello',
        { y: 'World' }
      ]
    };
    
    let { p, p: [x, { y }] } = obj;
    x // "Hello"
    y // "World"
    p // ["Hello", {y: "World"}]
    // 下面是另一个例子。
    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}
    

    上面代码有三次解构赋值,分别是对loc、start、line三个属性的解构赋值。注意,最后一次对line属性的解构赋值之中,只有line是变量,loc和start都是模式,不是变量

    3、字符串的解构赋值

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

    类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

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

    为什么

    4、数值和布尔值的解构赋值

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

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

    5、函数参数的解构赋值

    function add([x, y]){
      return x + y;
    }
    
    add([1, 2]); // 3
    
    
    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]
    

    6、圆括号问题

    自己看 欢迎幸运分享者分享

    7、用途

    1)交换变量的值
    let x = 1;
    let y = 2;
    
    [x, y] = [y, x];
    
    //别名问题
    const { a:b,c} = obj;
    
    2)从函数返回多个值
    // 返回一个数组
    
    function example() {
      return [1, 2, 3];
    }
    let [a, b, c] = example();
    
    // 返回一个对象
    
    function example() {
      return {
        foo: 1,
        bar: 2
      };
    }
    let { foo, bar } = example();
    
    3)函数参数的定义

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

    // 参数是一组有次序的值
    function f([x, y, z]) { ... }
    f([1, 2, 3]);
    
    // 参数是一组无次序的值
    function f({x, y, z}) { ... }
    f({z: 3, y: 2, x: 1});
    
    ???
    function add([a,b]){
        console.log(arguments[0]);
        console.log(arguments.length);
        return a+b;
    }
    console.log(add([2,3]));
    
    4)提取 JSON 数据

    自己看

    5)指定默认值
    jQuery.ajax = function (url, {
      async = true,
      beforeSend = function () {},
      cache = true,
      complete = function () {},
      crossDomain = false,
      global = true,
      // ... more config
    } = {}) {
      // ... do stuff
    };
    

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

    6)遍历 Map 结构

    任何部署了 Iterator 接口的对象,都可以用for...of循环遍历。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
    

    如果只想获取键名,或者只想获取键值,可以写成下面这样。

    // 获取键名
    for (let [key] of map) {
      // ...
    }
    
    // 获取键值
    for (let [,value] of map) {
      // ...
    }
    
    7)输入模块的指定方法

    加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰。
    const { SourceMapConsumer, SourceNode } = require("source-map");

    8、案例分析

    const self = this;
    let { mobile, followupName, startTime, endTime, type } = self.state.searchParams;
    omobile = mobile || '';
    ofollowupName = encodeURI(followupName || '');
    ostartTime = startTime || '';
    oendTime = endTime || '';
    otype = (type === undefined || type === null) ? '&type=' : self.handleType(type);
    

    上面代码还能怎么优化

    相关文章

      网友评论

          本文标题:(二)解构赋值

          本文链接:https://www.haomeiwen.com/subject/edrpiftx.html