对象解构
什么是解构
使用ES6的一种语法规则,将一个对象或数组的某个属性提取到某个变量中
const user = {
name: "kevin",
age: 11,
sex: "男",
address: {
province: "四川",
city: "成都"
}
}
// 先定义5个变量,然后从对象中读取同名属性,放到变量中
let { name, age, sex, address, abc = 123 } = user
console.log(name, age, sex, address, abc)
解构不会对被解构的目标造成任何影响
在解构中使用默认值
{同名变量 = 默认值}
非同名属性解构
{属性名:变量名}
const user = {
name: "kevin",
age: 11,
sex: "男",
address: {
province: "四川",
city: "成都"
}
}
// 先定义4个变量:name、age、gender、address
// 再从对象user中读取同名属性赋值(其中gender读取的是sex属性)
let { name, age, sex: gender = 123, address } = user
console.log(name, age, gender, address)
//解构出user中的name、province
//定义两个变量name、province
//再解构
const { name, address: { province } } = user;
console.log(name, address, province)
数组结构
const number = ["a",'b','c','d']
const {
0:n1,
2:n2
}= number
console.log(n1,n2)
const [n1,n2]= number
console.log(n1,n2)
const numbers = ["a", "b", "c", "d"];
const [n1, , , n4, n5 = 123] = numbers;
console.log(n1, n4, n5)
//嵌套的数组
const numbers = ["a", "b", "c", "d", [1, 2, 3, 4]];
// 得到numbers下标为4的数组中的下标为2的数据,放到变量n中
const [, , , , [, , n]] = numbers;
console.log(n)
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)
参数结构
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)
练习
1. 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)
2. 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);