zoukankan      html  css  js  c++  java
  • 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,或数字零,或 false,也会得到与 null 相同的结果,虽然 null 和二者不一样。

    注意:要同时判断 nullundefined、数字零、false 时可使用本法。

     

    var exp = null;

    if (typeof exp == "null")

    {

        alert("is null");

    }

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

     

    var exp = null;

    if (isNull(exp))

    {

        alert("is null");

    }

    VBScript 中有 IsNull 这个函数,但 JavaScript 中没有。

     

     

    --------------------------------------------------------------------------------

     

    以下是正确的方法:

     

    var exp = null;

    if (!exp && typeof exp != "undefined" && exp != 0)

    {

        alert("is null");

    }

    typeof exp != "undefined" 排除了 undefined

    exp != 0 排除了数字零和 false

     

    更简单的正确的方法:

     

    var exp = null;

    if (exp === null)

    {

        alert("is null");

    }

     

    --------------------------------------------------------------------------------

     

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

  • 相关阅读:
    用WebStorm运行Vue项目
    秋招圆满结束
    最新的秋招进度 10月21号
    来更新一下秋招的进度~
    华为三面完进池子啦~9月17日
    C++ 迭代器失效问题
    C++类相关问题(空类、多态、重载、继承)
    C++各种变量、类型的存储位置
    写一个面试中场景题的总结
    明天要面阿里HR面了
  • 原文地址:https://www.cnblogs.com/huangshoushi/p/5987799.html
Copyright © 2011-2022 走看看