javascript 判斷變量是否爲null

我的方法:java

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

有錯,請你們指出,謝謝。blog

 

如下是網上的一些資料:ip

http://dmewy.javaeye.com/blog/245300get

如下是不正確的用法:test

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

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 會使程序過於複雜。

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

相關文章
相關標籤/搜索