如何用js判斷null值

2021-10-01 06:18:28 字數 1040 閱讀 9253

我們在開發的時候經常會判斷乙個null值,那麼我們該如何去判斷呢?這篇文章就教大家如何用js判斷null值的方法,分別用兩種方法來對比一下如何正確用js判斷null值。

以下是不正確的方法:

var exp=null;

if(exp==null)

exp 為 undefined 時,也會得到與 null 相同的結果,雖然 null 和 undefined 不一樣。

注意:要同時判斷 null 和 undefined 時可使用如上方法。

var exp=null;

if(!exp)

如果 exp 為 undefined,或數字零,或 false,也會得到與 null 相同的結果,雖然 null 和二者不一樣。

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

var exp=null;

if(typeof exp=="null")

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

var exp=null;

if(!exp && typeof exp!="undefined" && exp!=0)

typeof exp!=「undefined」 排除了 undefined

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

更簡單的正確的方法:

var exp=null;

if(exp===null)

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

如何用js判斷null值

var exp null if exp null exp 為 undefined 時,也會得到與 null 相同的結果,雖然 null 和 undefined 不一樣。注意 要同時判斷 null 和 undefined 時可使用如上方法。var exp null if exp 為了向下相容,exp ...

hive 空值 null判斷

hive中空值判斷基本分兩種 1 null 與 n hive在底層資料中 如何儲存和標識null,是由 alter table name set serdeproperties serialization.null.format n 引數控制的 比如 1.設定 alter table name se...

c 判斷 值 是否為NUll

1 null null 關鍵字是表示不引用任何物件的空引用的文字值。null 是引用型別變數的預設值。那麼也只有引用型的變數可以為null,如果int i null,的話,是不可以的,因為int是值型別的。判斷 值 是否為null.html target self c 允許使用 或!來判斷是否為nu...