ECMAScript6 入门 变量的解析赋值

ES6 允许按照一定模式,先从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。

这句话的解释:第一步从数组或者对象中提取值,第二步将提取到的值对变量进行赋值 

数组的解构赋值

  重点:如果等号的右边的数据结构不存在Iterator接口,那么就会报错.

//以前,为变量赋值,只能直接指定值
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"

如果解构不成功,变量的值就等于undefined。
let [foo] = [];
let [bar, foo] = [1];
//foo的值都是undefined

对于Set的数据结构也是可以解构赋值
let [x, y, z] = new Set(['a', 'b', 'c']);

默认值

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 内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于undefined,默认值才会生效

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

let [x = 1] = [null];
x // null
因为null !== undefined ,所以默认值是没有效果

  如果默认值是一个表达式,那么这个表达式是惰性求值的,即只有在用到的时候,才会求值

function f() {
  console.log('aaa');
}

let [x = f()] = [1];
因为1 !== undefined,所以x是可以取到值的,那么对于表达式就不会去执行 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

对象的解构赋值

  1:对象解析与数组解析的不同点在于,数组的按照一定的顺序的,变量的取值取决于他的位置;而对象的属性没用顺序,变量必须与对象的属性名相同,才可以正确的取到值

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

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

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

  注释:与数组相同点

   1对象的解构赋值也是可以嵌套的,

   2另外对象也可以定义默认值,并且属性的值为undefined,默认值才会有效果

   3解析失败那么值为undefined。

注意点:注意是模式还是变量,变量采用的是逗号分开,模式后面紧跟的是冒号,我们只对变量赋值,不对模式赋值

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 arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3

数值,布尔值,字符串的解构赋值

  字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象,

  类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值

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

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

  解构赋值时,如果等号右边是数值和布尔值,则会先转为对象,数值和布尔值的包装对象都有toString属性

  重点:解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefinednull无法转为对象,所以对它们进行解构赋值,都会报错

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

 函数参数的解构赋值

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3
//那么肯定也可以使用默认值了
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]

  小提示:尽量解构赋值不要使用圆括号

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

用途

  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:遍历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

获取键名
for (let [key] of map) {
  // ...
}

获取键值
// 获取键值
for (let [,value] of map) {
  // ...
}

  6:输入模块的指定方法

const { SourceMapConsumer, SourceNode } = require("source-map");
不忘初心,不负梦想
原文地址:https://www.cnblogs.com/panrui1994/p/8995014.html