解构赋值中圆括号问题及解构赋值的用途

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

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

 

posted @ 2019-01-02 16:45  #小小佳  阅读(512)  评论(0编辑  收藏  举报