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 和二者不一樣。

注意:要同時判斷 nullundefined、數字零、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,可能返回 undefined,如果具體判斷 null 還是undefined 會使程序過於復雜。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM