JS中Null與Undefined的區別

  Undefined的類型只有一個值,即特殊的undefined。在使用var聲明變量但未對其加以初始化時這個變量的值就是undefined。對未初始化的變量執行typeof操做符會返回undefined值,而對未聲明的變量執行typeof操做符一樣也會返回undefined值。函數

  var oValue;  prototype

  alert(oValue == undefined); //output "true"  指針

 

  Null類型是第二個只有一個值的數據類型,這個特殊的值是null。從邏輯角度來看,null值表示一個空對象指針,而這也正是使用typeof操做符檢測null值時會返回"object"的緣由。對象

  alert(null == document.getElementById('notExistElement'));  原型鏈

  當頁面上不存在id爲"notExistElement"的DOM節點時,這段代碼顯示爲"true",由於咱們嘗試獲取一個不存在的對象。get

 

  用相等操做符==比較undefined和null時返回true;原型

  用全等操做符===比較undefined和null時返回true;io

 

  null表示"沒有對象",即該處不該該有值。典型用法是:console

  (1) 做爲函數的參數,表示該函數的參數不是對象。function

  (2) 做爲對象原型鏈的終點。

  Object.getPrototypeOf(Object.prototype)  // null

 

  undefined表示"缺乏值",就是此處應該有一個值,可是尚未定義。典型用法是:

  (1)變量被聲明瞭,但沒有賦值時,就等於undefined。

  (2) 調用函數時,應該提供的參數沒有提供,該參數等於undefined。

  (3)對象沒有賦值的屬性,該屬性的值爲undefined。

  (4)函數沒有返回值時,默認返回undefined。

  var i;  i

  // undefined  

 

  function f(x){console.log(x)} 

  f() // undefined  

 

 

  var  o = new Object(); 

  o.p // undefined  

 

  var x = f(); 

  x // undefined

相關文章
相關標籤/搜索