一、区别一下数组的解构赋值
- 对象的解构与数组有一个重要的不同。
数组的元素是按次序排列的,变量的取值由它的位置决定;
而对象的属性没有次序,变量必须与属性同名,才能取到正确的值
二、说明
- 对象的解构赋值的内部机制,是先找到同名属性,然后再赋给对应的变量。
- 真正被赋值的是后者,而不是前者。
- 前者主要是用于匹配
let obj = {
name: "wyt",
age: 18,
};
let { name: myname } = obj;
console.log("name:" + name);
console.log("myname:" + myname);
- 效果
- 解惑
大家可能会有疑惑
- 问题:为什么值(字符串wyt)被赋值给了myname而非name
- 答案:此处name仅仅是匹配模式,myname才是变量
即真正被赋值的是变量myname而非name
三、示例
1)简单的完整解构赋值
let obj = {
name: "wyt",
age: 18,
};
let { name, age } = obj;
console.log("name:" + name);
console.log("age:" + age);
- 效果
- 完整的代码
let obj = {
name: "wyt",
age: 18,
};
let { name: name, age: age } = obj;
console.log("name:" + name);
console.log("age:" + age);
2)简单的部分解构赋值(即按需解构)
let obj = {
name: "wyt",
age: 18,
};
let { name: name, age: age } = obj;
console.log("age:" + age);
- 效果
3)过度解构
一般未匹配到的变量常常被赋值为undefined
let obj = {
name: "wyt",
age: 18,
};
let { name, age, school } = obj;
console.log("obj:name" + name + ",age=" + age + ",school=" + school);
- 效果
4)复杂的完整解构
let stus_obj = {
stu_1: {
name: "wyt",
age: 18,
},
stu_2: {
name: "wyh",
age: 15,
},
};
let {
stu_1: { name: name1, age: age1 },
stu_2: { name: name2, age: age2 },
} = stus_obj;
console.log("stu_1:name=" + name1 + ",age=" + age2);
console.log("stu_2:name=" + name2 + ",age=" + age2);
- 效果
- 疑惑
- 大家可能会好奇两个问题
- 问题一:语句
let {
stu_1: { name: name1, age: age1 },
stu_2: { name: name2, age: age2 },
} = stus_obj;
中的stu_1,stu_2是否被赋值
- 答案:这里的stu_1,stu_2未被赋值,这里仅仅用于匹配
- 问题二:为什么上面的语句不可以写成语句
let {
stu_1: { name, age },
stu_2: { name, age },
} = stus_obj;
- 答案:Cannot redeclare block-scoped variable 'name'和'age'
let stus_obj = {
stu_1: {
name: "wyt",
age: 18,
},
stu_2: {
name: "wyh",
age: 15,
},
};
let {
stu_1,
stu_2,
stu_1: { name: name1, age: age1 },
stu_2: { name: name2, age: age2 },
} = stus_obj;
console.log(stu_1);
console.log("stu_1:name=" + name1 + ",age=" + age2);
console.log(stu_2);
console.log("stu_2:name=" + name2 + ",age=" + age2);
5)剩余运算符
let obj = {
name: "wyt",
age: 18,
school: "七中",
};
let { name, ...rest } = obj;
console.log("name:" + name);
console.log(rest);
- 效果
6)赋予默认值
let obj = {
name: "wyt",
age: 18,
};
let { name, age, school = "七中" } = obj;
console.log("name:" + name);
console.log("age:" + age);
console.log("school:" + school);
- 效果
四、应用
1)常用于解构对象中的方法
let { log, sin, cos } = Math;
const { log } = console;
log('hello')
2)常用于解构JSON对象里面所需的属性
let jsonData = {
id: 42,
status: "OK",
data: [867, 5309],
};
let { id, data } = jsonData;
console.log("id:" + id);
console.log("data:");
console.log(data);
- 效果