左右两边必须一样???? 也可以不一样

  1. //常规赋值
  2. let arr = [1,2,3]
  3. let a = arr[0]
  4. let b = arr[1]
  5. let c = arr[2]
  6. console.log(a,b,c) // 1 2 3
  7. //解构赋值
  8. let arr = [1,2,3]
  9. let [a,b,c] = arr // [a,b,c] = [1,2,3]
  10. console.log(a,b,c) // 1 2 3
  11. //右边比左边多
  12. let [a,b,c,d] = [1,2,3,'4',5]
  13. console.log(a,b,c,d) //1 2 3 "4"
  14. //左边比右边多
  15. let [a,b,c,d] = [1,2,3]
  16. console.log(a,b,c,d) //1 2 3 undefined
  17. //json对象
  18. let {a,b,c} = {a:1, d:'d', e:3}
  19. console.log(a,b,c) //1 undefined undefined 这个是错的,key 是不一样的
  20. let {a,b,c} = {a:1, b:'b', c:3}
  21. console.log(a,b,c) //1 "b" 3 这个是对的,所以,左右必须一样,key一样
  22. let {c, a, b} = {b:'b', c:3 , a:1}
  23. console.log(a,b,c) //1 "b" 3 这样也对,json对象的key是无序的
  24. //还可以这样,只要key一样就行,左右可以不一样多
  25. let {a,b,c,e,f} = {a:[1,2,3], b:'b is a string', c: {a:1,b:2,c:3}, d:0, e:999}
  26. console.log(a,b,c,e,f)
  27. //(3) [1, 2, 3] "b is a string" {a: 1, b: 2, c: 3} 999 undefined

右边必须是个合法的东西

声明和赋值不能分开

  1. //必须写在一行,下面的是不行的
  2. let [a,b]
  3. [a,b] = [1,2]
  4. console.log(a,b)
  5. //Uncaught SyntaxError: Missing initializer in destructuring declaration