一、对象解构
1.同名属性解构
使用ES6的一种语法规则,将一个对象或数组的某个属性提取到某个变量中,解构不会对被解构的目标造成任何影响
const user = {
name: "jimo",
age: 18,
sex: "男",
address: {
province: "四川",
city: "达州"
}
};
let name, age, sex, address, abc;
({ name, age, sex, address } = user);
console.log(name, age, sex, address);
简化为:
let { name, age, sex, address} = user;
console.log(name, age, sex, address);
2.解构中使用默认值
如果解构中可以添加变量并赋予默认值(当对象中有该值时就会使用对象的值)
let { name, age, sex, address, abc = 123 } = user
//let { name, age, sex = '女', address, abc = 123 } = user;sex赋值无效
console.log(name, age, sex, address, abc);
3.非同名属性解构
// 先定义4个变量:name、age、gender、address
// 再从对象user中读取同名属性赋值(其中gender读取的是sex属性,sex为undefined)
let { name, age, sex: gender = 123, address } = user;//对象中sex有值不会使用默认值
console.log(name, age, gender, address);
4.多重解构
const { name, address: { province } } = user;
// console.log(name, address, province);address不再是变量,而是被解构目标
console.log(name, province);
二、数组解构
1.基础
const numbers = ["a", "b", "c", "d"];
const [n1, n2, n3, n4] = numbers;
console.log(n1, n2, n3, n4);
如果想跳过解构后面内容
const [n1,,, n4] = numbers;
console.log(n1, n4);
2.多重解构
const numbers = ["a", "b", "c", "d", [1, 2, 3, 4]];
//得到numbers下标为4的数组中的下标为3的数据,放到变量n中
const [, , , , [, , n]] = numbers;
console.log(n);//3
const numbers = ["a", "b", "c", "d", {
a: 1,
b: 2
}];
//得到numbers下标为4的数组的属性a,赋值给变量A
const [, , , , { a: A }] = numbers;
// const { a: A } = numbers[4];灵活使用
console.log(A);// 1
3.展开运算符
在这里起剩余收集作用,放在末位
const user = {
name: "kevin",
age: 11,
sex: "男",
address: {
province: "四川",
city: "成都"
}
};
//解构出name,然后,剩余的所有属性,放到一个新的对象中,变量名为obj
// name: kevin obj : {age:11, sex:"男", address:{...}}
const { name, ...obj } = user;
console.log(name, obj);
const numbers = [324, 7, 23, 5, 3243];
// 得到数组前两项,分别放到变量a和b中,然后剩余的所有数据放到数组nums
const [a, b, ...nums] = numbers;
//const a = numbers[0], b = numbers[1], nums = numbers.slice(2);
console.log(a, b, nums);
4.练习
const article = {
title: "文章标题",
content: "文章内容",
comments: [{
content: "评论1",
user: {
id: 1,
name: "用户名1"
}
}, {
content: "评论2",
user: {
id: 2,
name: "用户名2"
}
}]
};
//解构出第二条评论的用户名和评论内容
// name:"用户名2" content:"评论2"
const datas = {comments :[,{
content,
user: {
name
}
}]} = article;
三、参数解构
function print({ name, age, sex, address: {
province,
city}
}) {//在参数中直接解构
console.log(`姓名:${name}`)
console.log(`年龄:${age}`)
console.log(`性别:${sex}`)
console.log(`身份:${province}`)
console.log(`城市:${city}`)
};
const user = {
name: "kevin",
age: 11,
sex: "男",
address: {
province: "四川",
city: "成都"
}
};
print(user);
function ajax({
method = "get",
url = "/"
} = {}) {
console.log(method, url)
};
ajax();//不传参也可以解构并设置默认值