zoukankan      html  css  js  c++  java
  • 解构赋值中圆括号问题及解构赋值的用途

    解构赋值虽然很方便,但是解析起来并不容易。对于编译器来说,一个式子到底是模式还是表达式,没有办法从一开始就知道,必须解析到(不能解析)等号才能知道。

    ES6的规则是:只要有可能导致解构的歧义,就不得使用圆括号。

    不能使用圆括号的情况:

    • 变量声明语句
    • 函数参数
    • 赋值语句的表达式

    可以使用圆括号的情况:赋值语句的非模式部分

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

    用途:

    1.交换变量的值

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

    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});

    4.提取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]

    5.函数参数的默认值

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

    6.遍历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

    7.输入模块的指定方法

    const { SourceMapConsumer, SourceNode } = require("source-map");
  • 相关阅读:
    zepto引用touch模块后,click失效
    cocos2dx中setContentSize与setDimensions在设置label显示区域上的区别
    convertToNodeSpace 与 convertToWorldSpace 的使用
    quick(3.2) UIListView扩展
    quick-cocos2d-x 游戏开发——StateMachine 状态机
    Lua学习笔记之字符串及模式匹配
    cocos2dx-3.x事件分发机制
    cocos2dx-Lua与Object的通讯机制
    cocos2dx-Lua与Java通讯机制
    Quick-cocos2dx容器层的使用
  • 原文地址:https://www.cnblogs.com/zsj-02-14/p/10209413.html
Copyright © 2011-2022 走看看