网络编程
位置:首页>> 网络编程>> JavaScript>> JS 中如何判断 null

JS 中如何判断 null

作者:chilleen  发布时间:2007-12-13 20:28:00 

标签:null,js,javascript

先来看看js中的Null类型表示什么?null用来表示尚未存在的对象,常用来表示函数企图返回一个不存在的对象,一般一个未定义的变量在初次使用时的类型就是null。

任何区别Javascript中的Null与Undefined

以下是不正确的用法:

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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com