在这里只是记录我平常没注意到的,不会涉及到所有的解构知识哈!!

不能对null和undefined进行解构

  1. let { _ } = null; // TypeError
  2. let { _ } = null; // TypeError

解构的时候可以给出默认值,开发中还是可以使用的

  1. let person = {
  2. name: 'xjx',
  3. age: 2
  4. }
  5. let {name, job='it'} = person
  6. console.log(name) // xjx
  7. console.log(job) // it

给事先声明的变量赋值

放到小括号中
注意分号很重要!!!!

  1. let pName, pAge;
  2. let person = {
  3. name: 'xjx',
  4. age: 2
  5. };
  6. ({name: pName, age: pAge} = person);
  7. console.log(pName, pAge) // xjx 2

嵌套解构,外层属性必须定义,无论是源对象还是目标对象

  1. let person = {
  2. name: 'xjx',
  3. age: {
  4. a: 1
  5. }
  6. };
  7. let {name, job: {a}} = person
  8. // VM75:7 Uncaught TypeError: Cannot read properties of undefined (reading 'a')
  9. let obj = {}
  10. (let {name, age: {a: obj.age.a}} = person )
  11. // Cannot set properties of undefined (setting 'a')