解构赋值语句
采用更加便捷的语法,访问数组和对象中的值,并将其赋值给变量。
关键点对象解构会找它的原型链。
//传统方法访问数组中的值
const arr = [1, 2, 3];
const a = arr[0],
b = arr[1],
c = arr[2];
//数组解构赋值
const arr = [1, 2, 3];
const [a,b,c] = arr;
//对象解构赋值
const obj = {a: 1, b: 2};
const {a, b} = obj;
//左侧的{ }会被视为块,所以需要加上()
let a, b;
({a, b} = {a: 1, b: 2});
变量初始化
//数组解构赋值的初始化
const [a = 0, b = 0 ,c = 0] = [1, 2, 3];
//对象解构赋值的初始化
const {a = 10, b = 5} = {a: 3};
const {a: a = 10, b: b = 5} = {a: 3};
实际应用
交换变量
let a = 1, b = 2;
[a, b] = [b, a];
rest操作符
//数组
const arr = [1, 2, 3, 4, 5];
const [a, b, ...c] = arr;
console.log(c); //[3,4,5]
//对象
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10
b; // 20
rest; // { c: 30, d: 40 }
函数传参
关键点函数传参中默认值{ }空数组很重要,可以保证无参数调用函数时不出错。
const user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
}
};
function foo({id = 1} = {}) {
console.log(id);
}