js中null和undefined

來源:互聯網
上載者:User

標籤:ar   使用   sp   div   bs   ef   as   type   js   

Undefined類型只有一個值,即undefined。當聲明的變數未被初始化時,變數的預設值為undefined。
Null類型也只有一個值,即null。null用來表示Null 物件指標。null 與對象引用有關係,表示為空白或不存在的對象引用。

var a;

alert(null == a); // true 

 

alert(null == undefined); // true 

ECMAScript認為undefined是從null派生出來的,所以把它們定義為相等的。但是,如果在一些情況下,我們一定要區分這兩個值,可以使用下面的兩種方法。

alert(null === undefined); //false

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


使用typeof方法undefined的類型為Undefined;null的類型是Object,null與undefined的類型是不一樣的,所以輸出"false"。而===代表絕對等於,在這裡null === undefined輸出false。

有以下幾種情況的,變數的值為undefined
1、變數定義,但沒有賦值,則變數的值為undefined
2、調用的方法沒有傳回值,在返回的值為undefined
3、對象的屬性值不存在,則傳回值為undefined,如:document.d

null 參與數值運算時其值會自動轉換為 0 ,因此,下列運算式計算後會得到正確的數值:
運算式:123 + null結果值:123
運算式:123 * null結果值:0 

undefined參與任何數值計算時,其結果一定是NaN。

js中null和undefined

聯繫我們

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