es6 解构赋值

什么是解构赋值

解构赋值是 es6 新增语法,通过解构赋值可以从对象(数组 / 字符串)中将属性值(元素 / 字符)提取出来,赋值或初始化给其他变量。

应用场景

赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//数组
var a, b;
[a, b] = [1, 2];//给 a b 变量赋值

var foo = ["one", "two", "three"];
var [one, two, three] = foo;//初始化 one two three 变量

//对象
var o = {p: 42, q: true};
var {p, q} = o;

console.log(p); // 42
console.log(q); // true

var a, b;

({a, b} = {a: 1, b: 2});//在使用对象字面量无声明解构赋值时是必须的

设置默认值

1
2
3
4
5
6
7
8
9
10
11
12
//数组
var a, b;

[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7

//对象
var {a:aa = 10, b:bb = 5} = {a: 3};

console.log(aa); // 3
console.log(bb); // 5

交换变量

1
2
3
4
var a = 1;
var b = 3;

[a, b] = [b, a];

接收函数返回值

1
2
3
4
5
6
7
function f() {
return [1, 2];
}

var a, b;
[a, b] = f(); //a = 1 b = 2
[, b] = f();//b = 2

将剩余数组赋值给一个变量

1
2
3
4
5
6
7
8
9
10
//数组
var [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]

//对象
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10
b; // 20
rest; // { c: 30, d: 40 }

注意

解构对象时会查找原型链

如果属性不在对象自身,将从原型链中查找

1
2
3
4
5
6
7
8
// 声明对象 和 自身 self 属性
var obj = {self: '123'};
// 在原型链中定义一个属性 prot
obj.__proto__.prot = '456';
// test
const {self, prot} = obj;
// self "123"
// prot "456"(访问到了原型链)

解构赋值是浅拷贝

1
2
3
4
5
6
7
8
var src = {a: {b: 1}};
var {a} = src;

a.b = 2;

console.log( JSON.stringify(a) );//{"b":2}
console.log( JSON.stringify(src) );//{"a":{"b":2}}