javascript的null和undefined

來源:互聯網
上載者:User

   null : 

   null是javascript的關鍵字,表示“空”,是不包含任何值的javascript內建對象。  

 alert(typeof(null));  //結果是object 

  可以在聲明變數時作為一個預留位置防止報錯(var a = null,表示a這個變數的值是“空”)。

  var a = null;  alert(a);        //結果是null

   undefined: 
   undefined不是javascript的關鍵字,它表示一個變數已經聲明但是沒有初始化

  var a;  alert(a);       //結果是undefined

 這裡我個人認為undefined本身是一個值,它的類型是"undefined",這麼說可能有些拗口,但是看下下面的例子:

  var a;  alert(typeof(undefined));   //結果undefined  這裡並不會把undefined當作一個沒有聲明的變數,否則會產生執行階段錯誤
  alert(typeof(a));        //結果undefined  alert(a == undefined);   //結果true    alert(a === undefined)  //結果ture, 一致性運算子只有當類型和值都相等的時候結果為true

 在做無值校正時,不建議用if (variable == undefined)的方法.因為javascript預設null和undefined的值是相等的

  alert(null == undefined);   //true

 最好用一致性運算子或者typeof判斷

  if (variable === undefined)  //或者  if (typeof(variable) == "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.