概念:解构赋值语法是一种 Javascript 表达式。通过解构赋值, 可以将属性/值从对象/数组中取出,赋值给其他变量。
var a, b, rest;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
[a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]
({ a, b } = { a: 1, b: 2 });
console.log(a); // 1
console.log(b); // 2
({a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4});
console.log(a); // 1
console.log(b); // 2
console.log(rest); // {c: 3, d: 4}
应用:使用解构赋值交换两个变量的值。
var a = 3;
var b = 8;
[a, b] = [b, a];
console.log(a); // 8
console.log(b); // 3
应用:解析一个从函数返回的数组
function fn() {
return [6, 8];
}
var a, b;
[a, b] = fn();
console.log(a); // 6
console.log(b); // 8
应用:忽略不感兴趣的值
function f() {
return [6, 7, 8];
}
var [a, , b] = f();
console.log(a); // 6
console.log(b); // 8
应用:将剩余数组赋值给一个变量
var [a, ...b] = [6, 7, 8];
console.log(a); // 6
console.log(b); // [7, 8]
应用:对象结构赋值
var people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith'
},
age: 35
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
},
age: 25
}
];
for (var {name: n, family: {father: f}} of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"