js判斷是否爲空

(1)typeof用法

typeof的運算數未定義,返回的就是 "undefined".

運算數爲數字 typeof(x) = "number"

字符串 typeof(x) = "string"

布爾值 typeof(x) = "boolean"

對象,數組 和null typeof(x) = "object"

函數 typeof(x) = "function"


(2)js判斷是否爲空

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

儘管如此,我們在 DOM 應用中,一般只需要用 (!exp) 來判斷就可以了,因爲 DOM 應用中,可能返回 null,可能返回 undefined,如果具體判斷 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 這個函數。

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