首頁  >  文章  >  web前端  >  JS中判斷null的方法分析

JS中判斷null的方法分析

高洛峰
高洛峰原創
2016-12-06 11:46:091385瀏覽

本文實例講述了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,或數字零,或 false,也會得到與 null 相同的結果,雖然 null 和二者不一樣。

注意:要同時判斷 null、undefined、數字零、false 時可使用本法。

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

   

為了向下相容,exp 為 null 時,typeof null 總回傳 object,所以不能這樣判斷。

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

   

VBScript 中有 IsNull 這個函數,但 JavaScript 中沒有。

以下是正確的方法:

var exp = null;
if (!exp && typeof exp != "undefined" && exp != 0)
{
  alert("is null");
}

   

typeof exp != "undefined" 排除了 undefined;

exp != 0 排除了數字零和 false。

更簡單的正確的方法:

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

   

儘管如此,我們在DOM 應用中,一般只需要用(!exp) 來判斷就可以了,因為DOM 應用中,可能返回null,可能返回null,可能返回undefined,如果具體判斷null 還是undefined 會使程式過於複雜。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn