ES6 解构赋值

1,140 阅读5分钟

1.1数组的解构赋值

1.1.1基本用法:

从数组中按变量位置提取值,对变量赋值,只要等号两边的模式相同,左边的变量就会被赋予对应的值。如果解构不成功变量的值为undefined。

// 简单例子
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"

let [x, , y] = [1, 2, 3];
x // 1
y // 3

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

// 不完全解构,等号左边部分匹配一部分右边的数组
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

如果等号右边转为对象后,不具备Iterator接口,或者本身不具备Iterator接口,会报错

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

// set,map 可以使用数组的解构赋值
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"

let map = new Map([
  ['name', '张三'],
  ['title', 'Author']
]);
let [foo] = map;
console.log(foo);

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

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

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
// x='a', y='b'
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

1.2对象的解构赋值

1.2.1基本用法

对象的属性没有次序,变量必须与属性同名。如果变量名在属性中不存在,解构失败,值为undefined。

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

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

对象的解构赋值,可以很方便地将现有对象的方法,赋值到某个变量。

const { log } = console;
log('hello') // hello

如果变量名与对象内属性名不一样,必须写出下面这种形式

对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。真正被赋值的是后者,而不是前者。

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined

可用于嵌套解构的对象。(遵循规则:对象遵循变量名等于对象内部属性,数组遵循对应位置赋值。)

let obj = {
  p: [
    'Hello',
    { y: 'World' }
  ]
};

let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"

如果解构模式是嵌套的对象,而且子对象所在的父属性不存在,那么将会报错

// 报错
let {foo: {bar}} = {baz: 'baz'};

对象的解构赋值可以取到继承的属性。

const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);

const { foo } = obj1;
foo // "bar"

1.2.2默认值

对象解构赋值可指定默认值,默认值生效条件是,对象的属性严格等于undefined。

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

var {x, y = 5} = {x: 1};
x // 1
y // 5

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

var {x: y = 3} = {x: 5};
y // 5

var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"

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

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

1.2.3注意点

1.如果要将一个已经声明的变量用于解构赋值,必须非常小心。

// 错误的写法
let x;
{x} = {x: 1};
// SyntaxError: syntax error
// JavaScript 引擎会将{x}理解成一个代码块
// 正确的写法
let x;
({x} = {x: 1});

2.数组本质是特殊的对象,因此可以对数组进行对象属性的解构。

let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3

1.3字符串的解构赋值

字符串被转换成类似数组的对象

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
let {length : len} = 'hello';
len // 5

1.4数值和布尔值的解构赋值

如果等号右边是数值和布尔值,则会先转为对象,可以获取到Number对象和Boolean对象的属性和方法。(只要等号右边的值不是对象或数组,就先将其转为对象)

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

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

1.5函数参数的解构赋值

函数参数可以使用解构赋值,也可以使用默认值

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

add([1]); // 4

1.6圆括号问题

解构赋值使用起来方便,但是编译器解析起来不方便,一个式子是模式还是表达式,没办法一开始就知道,必须解析到等号或者一直没有等号才知道。ES6中,只要有可能导致歧义,就不能使用圆括号。

1.6.1解构赋值不能使用圆括号的情况

  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 }] = [{}, {}];

1.6.2可以使用圆括号的情况

赋值语句的非模式部分可以使用圆括号

[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确

1.7用途

  1. 交换变量值
let x = 1;
let y = 2;

[x, y] = [y, x];
  1. 从函数返回多个值
// 返回一个对象

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();
  1. 函数参数的定义
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

  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]
  1. 函数参数默认值
function second({x, y = 2}) {
    console.log("x:"+x ,"y:"+ y);
}
second({}); // x:undefined y:2
second({x:100}); // x:100 y:2
second({x:100,y:200}); // x:100 y:200
  1. 遍历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
  1. 输入模块的指定方法

摘自:阮一峰