zoukankan      html  css  js  c++  java
  • 变量的解构赋值

    [外链图片转存失败(img-mkmGOxzQ-1565872507052)(https://upload-images.jianshu.io/upload_images/11158618-699f851f0cb96d1c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]

    数组的解构赋值:

    解构,就是从数组和对象中提取值,然后对变量进行赋值

    // ES5
    
    let a = 1;
    let b = 2;
    let c = 3;
    
    // ES6
    
    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 // []
    

    解构不成功,变量的值就等于undefined

    let [foo] = [];
    let [bar, foo] = [1];
    

    不完全解构

    let [x, y] = [1, 2, 3];
    x // 1
    y // 2
    
    let [a, [b], d] = [1, [2, 3], 4];
    a // 1
    b // 2
    d // 4
    
    // 报错
    let [foo] = 1;
    let [foo] = false;
    let [foo] = NaN;
    let [foo] = undefined;
    let [foo] = null;
    let [foo] = {};
    

    对于set结构,也可以使用数组的结构赋值

    let [x, y, z] = new Set(['a', 'b', 'c']);
    x // "a"
    

    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
    

    默认值

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

    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

    严格相等运算符(===),判断一个位置是否有值

    let [x = 1] = [undefined];
    x // 1
    
    let [x = 1] = [null];
    x // null
    

    当一个数组成员严格等于undefined,默认值才会生效

    function f() {
      console.log('aaa');
    }
    
    let [x = f()] = [1];
    
    let x;
    if ([1][0] === undefined) {
      x = f();
    } else {
      x = [1][0];
    }
    

    引用解构赋值的其他变量
    但该变量必须已经声明

    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
    

    对象的解构赋值

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

    不同之处在于没有次序

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

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

    let {foo} = {bar: 'baz'};
    foo // undefined
    

    可以赋值到现有的对象上

    // 例一
    let { log, sin, cos } = Math;
    
    // 例二
    const { log } = console;
    log('hello') // hello
    
    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
    
    let obj = {
      p: [
        'Hello',
        { y: 'World' }
      ]
    };
    
    let { p: [x, { y }] } = obj;
    x // "Hello"
    y // "World"
    
    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}
    

    嵌套赋值

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

    如果子对象所在的父属性不存在,那么会报错:

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

    继承性

    const obj1 = {};
    const obj2 = { foo: 'bar' };
    Object.setPrototypeOf(obj1, obj2);
    
    const { foo } = obj1;
    foo // "bar"
    

    默认值

    var {x = 3} = {};
    x // 3
    
    var {x, y = 5} = {x: 1};
    x // 1
    y // 5
    
    var {x: y = 3} = {};
    y // 3
    
    var {x: y = 3} = {x: 5};
    y // 5
    
    var { message: msg = 'Something went wrong' } = {};
    msg // "Something went wrong"
    

    对象的属性值严格等于undefined

    var {x = 3} = {x: undefined};
    x // 3
    
    var {x = 3} = {x: null};
    x // null
    
    // 错误的写法
    let x;
    {x} = {x: 1};
    // SyntaxError: syntax error
    

    JavaScript 引擎会将{x}理解成一个代码块,导致语法错误

    // 正确的写法
    let x;
    ({x} = {x: 1});
    
    // 表达式虽然毫无意义,但是语法是合法的,可以执行。
    ({} = [true, false]);
    ({} = 'abc');
    ({} = []);
    
    let arr = [1, 2, 3];
    let {0 : first, [arr.length - 1] : last} = arr;
    first // 1
    last // 3
    

    字符串也可以解构赋值

    const [a, b, c, d, e] = 'hello';
    a // "h"
    b // "e"
    c // "l"
    d // "l"
    e // "o"
    
    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
    

    函数参数的解构赋值

    function add([x, y]){
      return x + y;
    }
    
    add([1, 2]); // 3
    
    [[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的值。如果解构失败,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]
    
    [1, undefined, 3].map((x = 'yes') => x);
    // [ 1, 'yes', 3 ]
    

    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]; // 正确
    

    变量的解构赋值用途很多

    交换变量的值
    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]
    
    const { SourceMapConsumer, SourceNode } = require("source-map");
    
    // 获取键名
    for (let [key] of map) {
      // ...
    }
    
    // 获取键值
    for (let [,value] of map) {
      // ...
    }
    
    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
    

    学习目标:阮一峰ECMAScript 6 入门学习


    若本号内容有做得不到位的地方(比如:涉及版权或其他问题),请及时联系我们进行整改即可,会在第一时间进行处理。


    请点赞!因为你们的赞同/鼓励是我写作的最大动力!

    欢迎关注达叔小生的简书!

    这是一个有质量,有态度的博客

    [外链图片转存失败(img-wNOXt2Fa-1565872507054)(https://upload-images.jianshu.io/upload_images/11158618-9ab0d3fef85d80ce?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]

    版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
  • 相关阅读:
    [原创]设计模式建造者模式
    [原创]设计模式抽象工厂模式
    svn的branch/tag(转)
    [原创]设计模式访问者模式
    自定义安装python,退格,方向键无法正常使用(转)
    关于UDP 数据包长度的选择
    cent os 查看服务器信息
    【开源】QuickPager 分页控件的内部结构,和OO原则与设计模式
    【思路】表单控件和查询控件,整理一下思路。
    【测试】两种数据库,四种分页算法的效率比较
  • 原文地址:https://www.cnblogs.com/dashucoding/p/11932326.html
Copyright © 2011-2022 走看看