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

转载于:https://my.oschina.net/Tsybius2014/blog/1623467

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值