计算机网络/计算机科学与应用/系统/运维/开发

es6基础 - let 声明变量

1、let 声明的变量只在其所在代码块中有效

        {
            // 
            // let a = 10;
            var b = 1;
        }
        //console.log(a) //Uncaught ReferenceError: a is not defined
        //console.log(b) //1
        for(let i = 0; i < 10; i++){
            console.log(i)   
        }


2、不存在变量提升 变量要在声明后使用 否则报错

        //Cannot access 'foo' before initialization
        //console.log(foo)
        let foo = 2;
        console.log(foo)


3、暂时性死区

        //如果区块中存在let和const命令,则这个区块对这些命令声明的变量从一开始就形成封闭作用域。只要在声明之前就使用这些变量,就会报错
        //在代码块内  使用let命令声明变量之前,该变量都是不可用的 称为暂时性死区
        var tmp = 123;
        if(true){
            // tmp = 'abc'; // Cannot access 'tmp' before initialization
            // 上面代码tmp 称为暂时性死区
            let tmp;
        }


4、不允许重复声明

        function a(arg){
            let a = 10;
            // Uncaught SyntaxError: Identifier 'a' has already been declared
            // var a = 10;
            // 不能在函数内部重新声明参数
            // Uncaught SyntaxError: Identifier 'arg' has already been declared
            let arg;
        }



好的生活就是不瞎想,做得多,要得少,常微笑,懂知足。

评论

^