侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

javascript 判断变量是否为null

2024-05-08 星期三 / 0 评论 / 0 点赞 / 57 阅读 / 1589 字

个人方法: if(String(test) == "null") 有错,请大家指出,谢谢。 以下是网上的一些资料: (http://dmewy.javaeye.com/blog/245300) 以下

个人方法:

if(String(test) == "null")

有错,请大家指出,谢谢。

 

以下是网上的一些资料:

(http://dmewy.javaeye.com/blog/245300)

以下是不正确的用法:

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

exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。

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

如果 exp 为 undefined 或者数字零,也会得到与 null 相同的结果,虽然 null 和二者不一样。

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 会使程序过于复杂。

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

广告 广告

评论区