js判斷undefined和null

JS 中如何判斷 undefined


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

發佈了24 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章