变量

var 可以重复定义,不能限制修改,没有块级作用域
let 不能重复定义,变量,有块级作用域
const 不能重复定义,常量不能重新赋值,有块级作用域

建议永远抛弃var

  1. //重复赋值
  2. var a = 1
  3. a = 2
  4. console.log(a) //2
  5. let b = 1
  6. b = 2
  7. console.log(b)// 2
  8. const c = 1
  9. c = 2
  10. console.log(c) // Assignment to constant variable
  11. //重复定义
  12. var a1 = 1
  13. var a1 = 2
  14. console.log(a)
  15. let b1 = 1
  16. let b1 = 2
  17. console.log(b1) //Identifier 'b1' has already been declared
  18. const c1 = 1
  19. const c1 = 2
  20. console.log(c1)//Identifier 'c1' has already been declared
  21. //块级作用域
  22. if(1){
  23. var a2 = 1
  24. let b2 = 1
  25. const c2 = 1
  26. }
  27. console.log(a2)
  28. console.log(b2) // b2 is not defined
  29. console.log(c2) // c2 is not defined
  30. //let没有变量提升
  31. function a(){
  32. console.log(arr)
  33. console.log(brr);
  34. let arr = 1;
  35. var brr = 1;
  36. }
  37. a();// arr is not defined
  38. //const必须赋值
  39. const a //Uncaught SyntaxError: Missing initializer in const declaration

解构赋值

左右两边解构必须一样,右边必须是合法东西
左右两边赋值必须同步完成

  1. let [a,b,c] = [12,5,8]
  2. let {a,b,c} = {a:12,b:5,c:8}
  3. let [{a,b}] = [{"a":1,"b":2}]
  4. console.log(a,b) //1,2
  5. let [name,age] = ['niliv',3]
  6. let p = {name,age}
  7. console.log(p)
  8. // {name: "niliv", age: 3}
  9. let [n,{a,b},m] = [12,{a:1,b:2},12]
  10. console.log(a,n,m,b)
  11. let {a,b} = {1,2} //Unexpected token
  12. let [o,p];
  13. [o,p] = [1,2] //Missing initializer in destructuring declaration
  14. let [x,y] = [1,2]; //数组后面必须分号
  15. [x,y] = [y,x]
  16. //默认值
  17. let [c,b=2] = [3]
  18. //c 3
  19. //b 2
  20. let [x,y=2] = [3,4]
  21. //x 3
  22. //y 4
  23. let [m=2,n=3] = [undefined,null]
  24. //m 2
  25. //n null
  26. let {x,y=5} = {x:1}
  27. //x 1
  28. //y 5
  1. let {config:{method,url,data}}=response
  2. //相当于定义了4个变量