var let const区别

var let const的区别

  • var && let

    声明一个变量 var name="tony"

    function varTest() {
      var x = 31;
      if (true) {
        var x = 71;  // same variable!
        console.log(x);  // 71
      }
      console.log(x);  // 71
    }
    
    function letTest() {
      let x = 31;
      if (true) {
        let x = 71;  // different variable
        console.log(x);  // 71
      }
      console.log(x);  // 31
    }
    

    let 不允许重复声明一个变量

    <script>
        if (true) {
          let a;
          let a; // Uncaught SyntaxError: Identifier 'a' has already been declared
        }
    
        if(true){
          var d;
          var d;    //不会报错
        }
    
        if (true) {
          var c;
          let c; // Uncaught SyntaxError: Identifier 'c' has already been declared
        }
    
        if (true) {
          let d;
          var d; // Uncaught SyntaxError: Identifier 'd' has already been declared
        }
    </script>
    
    • const

      声明一个常量,并不是这个常量补课班,而是这个常量不能再次被赋值

      <script>
          /*不会报错,因为names1指向的地址不变,改变的只是内部数据*/
          const names1 = [];
                names1[0] = 1;
                names1[1] = 2;
                names1[2] = 3;
                names1[3] = 10;
          console.log(names1);
      
          /*出错,因为变量names2指向的地址不能发生改变,应始终指向[]所在的地址,[1,4]与[6,7]不是同一个地址*/
          const names2=[1,4];
                names2=[6,7];   //报错
      </script>
      
posted @ 2020-11-28 14:41  -至尊宝-  阅读(68)  评论(0编辑  收藏  举报