ES6-变量的结构赋值

1,153 阅读4分钟

一、数组

  • 解构:按照一定模式,从数组和对象中提取值,对变量进行赋值。
// 本质"模式匹配",只要等号两边模式相同,左边变量就会被赋对应值。
let [a, b, c] = [1, 2, 3];

let [foo, [[bar], baz]] = [1, [[2], 3]]
foo //1
bar //2
baz //3
  • 如果解构不成功,变量的值等于undefined
let [foo] = []
foo //undefined
  • 如果等号的右边不是数组(不可遍历的结构),将会报错。
let [foo] = 1;
let [foo] = null;
let [foo] = {};
  • 对于Set结构,也可以使用数组的解构赋值
let[x, y, z] = new Set(['a', 'b', 'c']);
x //'a'
  • 解构赋值允许指定默认值
let [foo = true] = [];
foo //true
  • 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

二、对象

  • 数组的元素时按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
let {bar, foo} = {foo:'aaa', bar:'bbb'};
foo //"aaa"
bar //"bbb"
  • 若变量没有对应的属性名,会导致取不到值,最后等于undefined。(解构失败)
let {baz} = {foo:"aaa"};
baz //undefined
  • 对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。
const {log} = console;
log('hello') //hello
  • 如果变量名与属性名不一致,必须写成这样:
let obj = {first:'hello', last:'world'};
let {first:f, last:l} = obj;
f //"hello"
l //"world"
  • 解构也可用于嵌套解构的对象
  • 对象的解构赋值可以取到继承的属性
const obj1 = {};
const obj2 = {foo:'bar'};
Object.setPrototypeOf(obj1,obj2);
const {foo} = obj1;
foo //"bar"
  • 如果要将一个已经声明的变量用于解构赋值,需要注意
let x;
{x} = {x:1}
//报错,因为js会将{x}理解成一个代码块,从而发生语法错误

({x} = {x:1})//正确执行

三、字符串

  • 字符串被换成了一个类似数组的对象,类似数组的对象都有一个length属性,因此可以对这个属性解构赋值。
const [a, b, c] = "hi!"
a //h
b //i
c //!

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

四、数值和布尔值

  • 解构赋值时如果等号右边是数值和布尔值,则会先转化为对象
let {toString: s} = 123;
s === Number.prototype.toString //true

let {prop:x} = undefined //TypeError
let {prop:y} = null //TypeError
//由于undefined和null无法转为对象,所以解构赋值报错

五、函数参数

function add([x, y]){
  return x + y;
}
add([1, 2]); // 3

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

六、圆括号问题

  • 以下三种解构赋值不得使用圆括号
  1. 变量声明语句
// 全部报错
let [(a)] = [1];

let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};

let { o: ({ p: p }) } = { o: { p: 2 } };
  1. 函数参数
// 报错
function f([(z)]) { return z; }
// 报错
function f([z,(x)]) { return x; }
  1. 赋值语句的模式
// 全部报错
({ 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]
  • 函数参数的默认值
jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};
  • 遍历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

// 获取键名
for (let [key] of map) {
  // ...
}
// 获取键值
for (let [,value] of map) {
  // ...
}
  • 输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map");