Javascript中Null和Undefined

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

    <script>
        //1.当声明变量未赋值时,那么变量的值就是undefined
        var x;
        //alert(x);

        //2.变量根本就没有声明
        //当使用了没有声明的变量时浏览器会报错 Uncaught ReferenceError: w is not defined
        //alert(w);
        //在使用变量之前,先校验该变量是否可用
        if(typeof(w) == 'undefined')
        {
            //alert('变量不可用');
        }

        //3.方法没有返回值的时候,接受到的值就是undefined
        var f1 = fun1();
        //alert(f1);
        function fun1() {
        }
        
        //---------------------------------------------------------------------------------
        //1.null值表示指向了一个"空对象"
        //一般一个对象使用完毕,需要显示告诉浏览器可以被垃圾回收的情况下,需要显示把变量赋值为null,这样这个变量所指向
        //的对象就可以被垃圾回收了


        /*
        无论变量的值是null值,还是undef都表示该变量不可用。
        所以再使用某些变量前可以对变量做校验,判断该变量是否可用
        */

        //校验变量是否可用
        var n1 = 1;
        if (typeof(n1) != 'undefined' && n1 != null) {
            alert('该变量可用');
        } else {
            alert('该变量不可用');
        }

    </script>

</head>
<body>
    
</body>
</html>
发布了60 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_24432127/article/details/89440440