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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章