js中null 和undifined的判断

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");
}
typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined"
 
以下是正确的用法:
var exp = undefined;
if (typeof(exp) == "undefined")
{
    alert("undefined");

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


注意:判读一个不存在的值时可以采用typeof(notdefinevar)==‘undefined’;
————————————————
版权声明:本文为CSDN博主「gaojie1190」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/gaojie1190/java/article/details/83840563

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值