变量定义let、consot、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>
<style>
    .father {
        display: flex;
        height: 30px;
    }

    .father .item {
        flex: 1;
        background-color: pink;
    }
</style>

<body>
    <div class="father">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
    <script type="text/javascript">
        // //对于没有声明的变量报错
        // console.log(asdas);//报错

        //const定义一定要赋值
        // var a;

        // let b;
        // const c = [1, 2, 3];

        ////全局变量
        //// 例子1 直接定义a='hello';
        // (function () {
        //     (function () {
        //         a = 'hello';
        //     })()
        //     console.log(a);//hello
        // })();

        //     console.log(a);//hello

        // //如果外面定义了var变量 那么函数内的变量应该是赋值而不是定义 不存在函数内的a变为全局函数
        // //用严格模式验证
        // "use strict";
        // var a = 'hehe';
        // (function () {
        //     a = 'hello';
        //     console.log(a);//不报错
        // })();
        // console.log(a);//不报错


        // //例子2 在函数外使用var,会变成全局变量,当然你也可以使用window.a
        // var a = {};
        // console.log(a === window.a)//true


        // //const不能被重新赋值,但是引用对象类型的属性可以
        // // c = null;报错
        // c.a = 12;
        // console.log(c);//[1, 2, 3, a: 12]




        // // let和const不能重复定义变量
        // let c = 1;
        // if (true) {
        //     c = 2;
        // }
        // console.log(c);//1

        // (function () {
        //     c = 3;

        // })()
        // console.log(c);//3 这里能访问是作用域链的关系
        // // let c = 3; //报错


        // //var存在变量提生,所谓变量提升就是将定义往顶部提,但是没有赋值,值为undefined
        // console.log(d)//undefined
        // d = 2;
        // console.log(d)//2
        // var d = 1;
        // console.log(d)//1

        // //暂时性死区,let和const没有变量提升(使用"use strict";发现实际上编译器已经定义b,但不给予使用)
        // e = 2;
        // const e;

        //特殊定义
        // var f = 2
        // var g = f = 88
        // console.log(f)//88
        // console.log(g)//88

        // var f =2;
        // var g;
        // g=88;
        // f=88;
        // console.log(f)//88
        // console.log(g)//88











    </script>
</body>

</html>

文章作者: iamfugui
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iamfugui !
评论
  目录