在这里只是记录我平常没注意到的,不会涉及到所有的解构知识哈!!
不能对null和undefined进行解构
let { _ } = null; // TypeError
let { _ } = null; // TypeError
解构的时候可以给出默认值,开发中还是可以使用的
let person = {
name: 'xjx',
age: 2
}
let {name, job='it'} = person
console.log(name) // xjx
console.log(job) // it
给事先声明的变量赋值
放到小括号中
注意分号很重要!!!!
let pName, pAge;
let person = {
name: 'xjx',
age: 2
};
({name: pName, age: pAge} = person);
console.log(pName, pAge) // xjx 2
嵌套解构,外层属性必须定义,无论是源对象还是目标对象
let person = {
name: 'xjx',
age: {
a: 1
}
};
let {name, job: {a}} = person
// VM75:7 Uncaught TypeError: Cannot read properties of undefined (reading 'a')
let obj = {}
(let {name, age: {a: obj.age.a}} = person )
// Cannot set properties of undefined (setting 'a')