zoukankan      html  css  js  c++  java
  • JS 中判断空值 undefined 和 null

    1.JS 中如何判断 undefined

    JavaScript 中有两个特殊数据类型:undefined 和 null,下节介绍了 null 的判断,下面谈谈 undefined 的判断。

    以下是不正确的用法:

    var exp = undefined;
    if (exp == undefined)
    {
        alert("undefined");
    }

    exp 为 null 时,也会得到与 undefined 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 undefined 和 null 时可使用本法。

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

    以下是正确的用法:

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

    2.JS 中如何判断 null

    以下是不正确的用法:

    var exp = null; 
    if (exp == null) 
    { 
    alert(“is null”); 
    }
    
    exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 null 和 undefined 时可使用本法。
    
    var exp = null; 
    if (!exp) 
    { 
    alert(“is null”); 
    }
    
    如果 exp 为 undefined 或者数字零,也会得到与 null 相同的结果,虽然 null 和二者不一样。注意:要同时判断 null、undefined 和数字零时可使用本法。
    
    var exp = null; 
    if (typeof(exp) == “null”) 
    { 
    alert(“is null”); 
    }
    
    为了向下兼容,exp 为 null 时,typeof 总返回 object。
    
    var exp = null; 
    if (isNull(exp)) 
    { 
    alert(“is null”); 
    }
    
    JavaScript 中没有 isNull 这个函数。

    以下是正确的用法:

    var exp = null; 
    if (!exp && typeof(exp)!=”undefined” && exp!=0) 
    { 
    alert(“is null”); 
    } 

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

  • 相关阅读:
    PHP页面静态化
    PHP实现单文件、多文件上传 封装 面向对象实现文件上传
    PHP MYSQL
    MySQL 数据表
    MySQL基础
    DOM事件处理程序-事件对象-键盘事件
    JS--显示类型转换Number—隐式类型转换
    JS的数据类型
    JS属性读写操作+if判断注意事项
    Javascript进阶篇——总结--DOM案例+选项卡效果
  • 原文地址:https://www.cnblogs.com/panchanggui/p/14890067.html
Copyright © 2011-2022 走看看