js中null 和undefined的區別

來源:互聯網
上載者:User

標籤:

參考文章:http://www.jb51.net/article/27937.htmhttp://www.cnblogs.com/eastday/archive/2010/03/03/1677324.html

首先:

null == undefined ;  // true , ECMAScript認為undefined是從null派生出來的,所以把它們定義為相等的。

null === undefined ;  // false, 但是它們兩個

Null
typeof null ; // objectnull是一個對象,但是為空白。
null是javascript保留關鍵字。

parseInt(null) ; //NaN
但是null在參與運算時其值會自動轉換為0。
123 + null ; // 123
123 * null ; 0
undefined  
typeof undefined ; // "undefined"

undefined 是全域對象(window)的一個特殊屬性,其值是未定義的。
undefined in window ; //true
null in window ; // false

undefined不是javascript的保留關鍵字。
parseInt(undefined) ; // NaN
undefined參與任何數值計算時,其結果一定是NaN.

另 : 

NaN是全域對象(window)的另一個特殊屬性。Infinity也是。但是這些特殊屬性都不是Javascript的保留關鍵字。

關於undefined的效能問題:(漲姿勢了!)

當我們在程式中使用undefined值時,實際上使用的是window對象的undefined屬性。
同樣,當我們定義一個變數但未賦予其初始值,例如:
var aValue; 這時,JavaScript在所謂的先行編譯時會將其初始值設定為對window.undefined屬性的引用, 於是,當我們將一個變數或值與undefined比較時,實際上是與window對象的undefined屬性比較。這個比較過程中,JavaScript會搜尋window對象名叫‘undefined‘的屬性,然後再比較兩個運算元的引用指標是否相同。
由於window對象的屬性值是非常多的,在每一次與undefined的比較中,搜尋window對象的undefined屬性都會花費時 間。在需要頻繁與undefined進行比較的函數中,這可能會是一個效能問題點。因此,在這種情況下,我們可以自行定義一個局部的undefined變數,來加快對undefined的比較速度。
eg :
function anyFunc() 
{ 
  var undefined; //自訂局部undefined變數 
  if(x == undefined) //範圍上的引用比較 
  while(y != undefined) //範圍上的引用比較 
}; 

其中,定義undefined局部變數時,其初始值會是對window.undefined屬性值的引用。新定義的局部undefined變數存在與該函數的範圍上。在隨後的比較操作中,JavaScript代碼的書寫方式沒有任何的改變,但比較速度卻很快。因為範圍上的變數數量會遠遠少於window對象的屬性,搜尋變數的速度會極大提高。 
這就是許多前端JS架構為什麼常常要自己定義一個局部undefined變數的原因! 

 

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.