ES6系列之解构

本系列是在平时阅读、学习、实际项目中有关于es6中的新特性、用发的简单总结,目的是记录以备日后温习;本系列预计包含let/const、箭头函数、解构、常用新增方法、Symbol、Set&Map、Proxy、reflect、Class、Module、Iterator、Promise、Generator、async/await。。。

解构个人理解就是相同模式,可以对应赋值,属于“模式匹配”

基本用法

// 基本用法
    let [a, b] = [1, 2]; // x = 1, y = 2
    let [, c] = [3, 4]; // c = 4
    let [d, e] = [1]; // d = 1, e = undefined

    // 与...结合使用
    let [f, ...tail] = [1, 2, 3, 4]; // e = 1, tail = [2, 3, 4]

    // 等号右侧为非可遍历对象,则抛出异常
    let [g, h] = null; // Uncaught TypeError: null is not iterable
    // 设定默认值
    let [i = 'i'] = []; // i = 'i'

对象解构

// 基本用法
    let {a, b} = {a: 'aa', b: 'bb'}; // a = 'aa', b = 'bb'

    // 如果变量名和属性名不一致
    let {foo: bar} = {foo: 1, baz: 2}; // bar = 1 (注意:这里foo这个变量仍然没有被定义,如果试图访问变量foo,则会抛出异常: Uncaught ReferenceError: foo is not defined)

    // 上面的异常情况其实是证明对象的解构其实是下面这种写法的简写,也就是说: 对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量
    let {a: _$, b: $_} = {a: 1, b: 2}; // _$ = 1, $_ = 2

    // 指定默认值
    let {c, d = 'dd'} = {c: 'cc'} // c = 'cc', d = 'dd'

    // 下面这种情况会抛出错误
    let x;
    {x} = {x: 'xx'}; // Uncaught SyntaxError: Unexpected token =
    // 因为上面的情况开头的{会被解析为代码块,应该改成这样
    ({x} = {x: 'xx'});

字符串解构

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

数值、布尔值解构

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]

function move1({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}

move1({x: 3, y: 8}); // [3, 8]
move1({x: 3}); // [3, undefined]
move1({}); // [undefined, undefined]
move1(); // [0, 0]

// 上面函数move和move1默认值的区别是: move的参数是一个对象,并为参数对象的属性指定默认值;move1的参数是一个对象,并为参数指定默认值,该默认值是{x: 0, y: 0}

用途

(1)交换变量值

let x = 1;
let y = 2;

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

(2)函数返回多个值

function example() {
  return [1, 2, 3];
}
let [a, b, c] = 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;

(5)为函数参数指定默认值(这个之前的例子已经有所体现)

原文地址:https://www.cnblogs.com/innooo/p/10452271.html