JavaScript中Null和undefind區別

來源:互聯網
上載者:User

標籤:lan   ber   log   數值計算   hello   程式碼範例   類型   nat   iad   

公眾號原文

Javascript有5種基本類型:Boolean,Number,Null,Undefined,String;和一種複雜類型:Object(對象);

undefined:只有一個值,及特殊的undefined。在使用var聲明變數但未對其初始化時,這個變數的值是undefined,簡言之,undefined就是表示變數申明了但未初始化時的值。

注意:尚未聲明的值直接alert其值會報錯而不是顯示undefined;但是如果一個申明了未賦值的變數與未聲明的變數所顯示的typeof結果是一樣的--->undefined

程式碼範例:

<script type="text/javascript">var str;alert(typeof str);//undefinedalert(typeof message);//undefined</script>

 

undefined在參與數值運算時一定是NAN,在與字串拼接相加時則直接顯示undefined;

程式碼範例:

<script type="text/javascript">var b;alert(b+3);//輸出 NANalert(b+‘3‘);//輸出 undefined3</script>

 

null:示準備用來儲存對象,還沒有真正儲存對象的值。從邏輯角度看,null值表示一個Null 物件指標。也就是說 null是相對於對象而言的,所以typeof(null) 為object。

null在參與數值計算時其值自動轉換為0,而進行字串相加拼接時會以字串“null”的方式顯示

程式碼範例:

<script type="text/javascript">var a=null;alert(null+3+5);//8alert(null+‘hellow‘);//nullhellowalert(null+3+‘hellow‘);//3hellowalert(null+‘hellow‘+3);//nullhellow3</script>

  

聯絡:alert(null=undefined);//true   ECMAScript認為undefined是由null派生出來的,所以將他們定義為相等。

如何區分?

alert(typeof null == typeof undefined);alert(null === undefined);

 

 

JavaScript中Null和undefind區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.