ES6 变量的解构赋值

210 阅读2分钟

1.数组的解构赋值

   (1)为变量赋值 let [a,b,c] = [1,2,3]

     (2)  如果等号的右边不是数组(或者严格地说,不是可遍历的结构,参见《Iterator》一章),那么将会报错。

// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

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

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

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

2.对象的解构赋值

(1)对象的解构与数组的解构不一样,数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值

let { bar, foo, fish } = { foo: 'aaa', bar: 'bbb',fish: {weight: '111', color: 'red'} };
foo // "aaa"
bar // "bbb"
fish // {weight: '111', color: 'red'}

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

如果变量名与属性名不一致,必须写成下面这样。

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa" foo是匹配的模式,baz才是变量。真正被赋值的是变量baz,而不是模式foo。
foo // undefind

let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'

(2) 默认值生效的条件是,对象的属性值严格等于undefind。

var {x = 3} = {x: undefined};
x // 3

var {x = 3} = {x: null};
x // null

3.字符串的解构赋值

(1)字符串被转换成了一个类似数组的对象。类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

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

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

4.用途

(1)交换变量的值

let x = 1;
let y = 2;

[x, y] = [y, x];

(2)从函数返回多个值

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

(3)函数参数的定义

(4)提取json数据

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

(5)函数参数的默认值

(6)遍历map解构 (任何部署了 Iterator 接口的对象,都可以用for...of循环遍历。)

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