如何用js判斷null值
阿新 • • 發佈:2018-12-07
我們在開發的時候經常會判斷一個null值,那麼我們該如何去判斷呢?這篇文章就教大家如何用js判斷null值的方法,分別用兩種方法來對比一下如何正確用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(!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 會使程式過於複雜。