## 数组解构
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
// 结合 rset 扩展运算符,分配其余值
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
// 如果解构不成功,变量的值就等于undefined
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
## 对象解构
// 对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值
let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined
const [,,{name}] = [
{id:1, name: 'apple'},
{id:2, name: 'peach'},
{id:3, name: 'banana'}
]
name // 'banana'
// 老方法,声明一个中间变量作为媒介,然后交换两个变量的值
let arr = ['apple', 'peach', 'banana'];
let temp = arr[1];
arr[1] = arr[2];
arr[2] = temp ;
arr // ['apple', 'banana', 'peach'];
// es6解构,直接交换,无需中间变量
let arr2 = ['apple', 'peach', 'banana'];
[arr2[1], arr2[2]] = [arr2[2], arr2[1]];
arr2 // ['apple', 'banana', 'peach']
const {apple, peach, bba:banana} = {
apple: 'apple',
peach: 'peach',
bba: 'banana'
}
apple; // 'apple'
peach; // 'peach'
banana; // 'banana'
function fn({name, age}) {
console.log(name);
console.log(age);
}
let person = {
name: '李白',
age: 2000
}
fn(person);
// '李白'
// 2000
上边案例中,如果 person 对象没有 name属性(或name值为undefined),可以在定义函数时,参数解构时赋一个默认值,如:
function fn({name='杜甫', age}) {
console.log(name);
console.log(age);
}
let person = {
age: 2000
}
fn(person);
// '杜甫'
// 2000
let person2 = {
name: undefined,
age: 2000
}
fn(person2);
// '杜甫'
// 2000
const fruits = {
apple: 'this is an apple',
peach: 'this is a peach'
}
const key = 'peach';
const {[key]:fruit} = fruits;
fruit; // 'this is a peach'