美文网首页
js 如何用js判断null值

js 如何用js判断null值

作者: 七號7777 | 来源:发表于2020-03-04 16:45 被阅读0次

    参考文章:https://blog.csdn.net/bbenst/article/details/83625830

    方法一
    要同时判断 null 和 undefined 时

    var exp=null;
    if(!exp){
        alert("is null");
    }
    

    方法二
    要同时判断 null、undefined、数字零、false 时

    var exp=null;
    if(typeof exp=="null"){
        alert("is null");
    }
    

    方法三
    为了向下兼容,exp 为 null 时,typeof null 总返回 object,所以不能这样判断。

    //  typeof exp!=“undefined” 排除了 undefined      exp!=0 排除了数字零和 false。
    var exp=null;
    if(!exp && typeof exp!="undefined" && exp!=0){
        alert("is null");
    }
    

    一般只需要用 (!exp) 来判断就可以了,因为 DOM 应用中,可能返回 null,可能返回 undefined,如果具体判断 null 还是 undefined 会使程序过于复杂。

    相关文章

      网友评论

          本文标题:js 如何用js判断null值

          本文链接:https://www.haomeiwen.com/subject/hkrblhtx.html