2021-03-23 es6相关语法 let/const 声明变量 与 var 声明变量的区别

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>
        <script>
            //let: 声明变量  / 只在所在代码块(块级作用域)内有效
            //const: 声明常量  /  不可更改

            let a1 = 10
            const PI = 3.1415


            //块级作用域 : 提前声明仅限当前所在块内
            //例 : 

            // fn() //es6语法.html:21 Uncaught TypeError: fn is not a function /at es6语法.html:21

            {
                //这是一个块级作用域
                fn() // 1 /es6语法.html:26

                function fn() {
                    console.log(1);
                }

            }
            fn() // 1 /es6语法.html:26 

            //例 : let 与 var 的区别
            //let 声明的变量不能被前声明
            {
                var a2 = 10
                console.log(a2); //es6语法.html:39 /10
            }
            console.log(a2); //es6语法.html:41 /10
            {
                // console.log(b2); //不能被提前声明 /*es6语法.html:43 Uncaught ReferenceError: Cannot access 'b2' before initialization at es6语法.html:43*/
                let b2 = 20
                console.log(b2); /*es6语法.html:44 20*/
            }
            //console.log(b2);  /* es6语法.html:46 Uncaught ReferenceError: b2 is not defined.at es6语法.html:46*/

            //const 声明的常量无法被提前声明
            //const 声明的常量无法修改
            {
                //console.log(a3);
                const a3 = 20
                //a3 = 21 //es6语法.html:55 Uncaught TypeError: Assignment to constant variable.at es6语法.html:55
            }
            
			//let 声明的变量名称不能重复
            {
                let a4 = 10
                /* let a4 = 20  //Uncaught SyntaxError: Identifier 'a4' has already been declared */
            }

            {
                for (var i = 0; i < 10; i++) {
                    setTimeout(() => {
                        console.log(i); //输出10个10
                    }, 0);
                }
                for (let j = 0; j < 10; j++) {
                    console.log(j); // 0 1 2 3 4 5 6 7 8 9 
                }
            }
			
			//暂时性死区
            {
                var a5 = 20
                {
                    //console.log(a5); //es6语法.html:78 Uncaught ReferenceError: Cannot access 'a5' before initialization
                    let a5 = 10
                    console.log(a5); // 10
                }
                console.log(a5); // 20
            }
        </script>
    </body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值