JS中如何判斷null

來源:互聯網
上載者:User

標籤:程式   mil   vbscript   time   roman   family   javascrip   java   使用   

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,可能返回 undefined,如果具體判斷 null 還是undefined 會使程式過於複雜。

JS中如何判斷null

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.