JavaScript学习笔记:判断变量是否为undefined,判断变量和函数是否声明

测试了三个功能:

1、判断变量是否为undefined

2、判断变量是否声明

3、判断函数是否声明

代码如下:

<html>
<head>
  <title>JavaScript学习</title>
</head>
<body>
</body>
<script>

    //1 判断变量是否为undefined
    
    //1.1 a是undefined
    var a = undefined;
    if (a === undefined) {
        console.log("a是undefined");
    } else {
        console.log("a不是undefined");
    }
    
    //1.1 b不是undefined
    var b = null;
    if (b === undefined) {
        console.log("b是undefined");
    } else {
        console.log("b不是undefined");
    }
    
    //2 判断变量是否存在
    
    //2.1 变量c不存在
    var cExist = false;
    try {
        if (typeof(c) == "undefined") {
            cExist = false;
        } else {
            cExist = true;
        }
    } catch (ex) {
    }
    if (cExist) {
        console.log("变量c存在");
    } else {
        console.log("变量c不存在");
    }
    
    //2.2 变量d存在
    var d = 0;
    var dExist = false;
    try {
        if (typeof(d) == "undefined") {
            dExist = false;
        } else {
            dExist = true;
        }
    } catch (ex) {
    }
    if (dExist) {
        console.log("变量d存在");
    } else {
        console.log("变量d不存在");
    }
    
    
    //3 判断函数是否存在
    
    //3.1 函数e不存在
    var eExist = false;
    try {
        if (typeof(eval(e)) == "function") {
            eExist = true;
        }
    } catch(ex) { 
    }
    if (eExist) {
        console.log("函数e存在");
    } else {
        console.log("函数e不存在");
    }
    
    //3.2 函数f存在
    function f() { 
    }
    var fExist = false;
    try {
        if (typeof(eval(f)) == "function") {
            fExist = true;
        }
    } catch(ex) { 
    }
    if (fExist) {
        console.log("函数f存在");
    } else {
        console.log("函数f不存在");
    }

</script>
</html>

我使用的Chrome版本为 Version 63.0.3239.132 (Official Build) (64-bit)

运行结果如下:

END

猜你喜欢

转载自my.oschina.net/Tsybius2014/blog/1623467