对象解构语法
1.同名属性
// var/let/const{属性名}=被解构的对象
const user = {
name: "abc",
age: 18,
sex: "男",
address: {
province: "重庆",
city: "重庆"
}
}
let { name, age, sex, address} = user;
console.log(name, age, sex, address);
也可以多添加一个属性
const user = {
name: "abc",
age: 18,
sex: "男",
address: {
province: "重庆",
city: "重庆"
}
}
let { name, age, sex, address, a=123} = user;
console.log(name, age, sex, address, a);
2.非同名属性
// var/let/const{属性名:变量名}=被解构的对象
const user = {
name: "abc",
age: 18,
sex: "男",
address: {
province: "重庆",
city: "重庆"
}
}
let { name, age, sex: gender, address, abc = 123 } = user
console.log(name, age, gender, address, abc)
//gender读取的是sex的值,相当于把sex属性名变成了gender
3.把一个对象解构成两个对象
const obj = {
name: "第一个对象",
age: 18,
province: {
name: "第二个对象",
age: 19
}
};
// 解构出name和age,然后剩余的所有属性解构到另一个新的对象中变量名为obj1
const { name, age, ...obj1 } = obj;//...是展开运算符
console.log(name, age, obj1);
数组解构
首先我们要清楚,数组实质上就是一个对象,所以我们可以用解构对象的方式来解构数组
const numbers = [1, 2, 3, 4]; console.log(numbers);
const numbers = [1, 2, 3, 4];
const {
0: n1,
1: n2
} = numbers;
console.log(n1, n2);
0,1代表的是属性名,属性值结构到n1,n2中。 如果我们想要解构数组的第一项和最后一项那么可以这样写
const numbers = [1, 2, 3, 4];
const {
0: n1,
3: n2
} = numbers;
console.log(n1, n2);
但是这样的写法是对象解构,所以es6提供了数组解构的专门语法
const numbers = [1, 2, 3, 4];
const [n1, n2] = numbers;
console.log(n1, n2);
这里代表按顺序把数组的项解构,n1表示第一项,n2表示第二项。那么如果我们想解构第一项和最后一项呢。可以在解构过程中,把不要的项空着。
const numbers = [1, 2, 3, 4];
const [n1, , , n4] = numbers;
console.log(n1, n4);
数组中有数组或者对象的结构 1.数组中有数组
const numbers = [1, 2, 3, 4, [5, 6, 7]];
// 希望解构出numbers的第一项n1和第五项中的第二项n2
const [n1, , , , [, n2]] = numbers;
console.log(n1, n2);
2.数组中有对象
const numbers = [
1,
2,
3,
4,
5,
{
name: "abc"
}
];
// 希望解构出numbers中的第一项n1和第六项中的name
const [n1, , , , , { name }] = numbers;
console.log(n1, name);
对象中有数组和对象的解构,和这个类似。
交换两个变量的值 以前如果要交换两个变量的值,我们需要第三个变量来实现。但是现在有了解构过后,就变得非常简单了。
//交换a,b的值
let a = 1, b = 2;
[b, a] = [a, b]
console.log(a, b)
参数解构
可以在函数的形参里直接解构
function print({name,age,sex,province,city}){
console.log(`姓名:${name}`);
console.log(`年龄:${age}`);
console.log(`性别:${sex}`);
console.log(`省份:${province}`);
console.log(`城市:${city}`);
}
const obj = {
name : 'abc',
age : 18,
sex : '男',
province : "重庆",
city : "重庆"
};
print(obj);
function ajax({ method = "get", url = "/" }) {
console.log(method, url);
}
ajax({
method: "post",
url: "/abc/123"
});
如果在函数调用时什么都不传会报错
function ajax({ method = "get", url = "/" }) {
console.log(method, url);
}
ajax();
解决方法是给一个参数默认值
function ajax({ method = "get", url = "/" } = {}) {
console.log(method, url);
}
ajax();