JS中六種資料類型(一)——undefined (轉)

來源:互聯網
上載者:User

標籤:個數   先來   比較   null   javascrip   例子   bsp   define   var   

 JS中有6種資料類型:Undefined、Null、Boolean、Number、String和Object。JS中不支援任何建立自訂類型的機制,而所有值最終都將是這6種資料類型。其資料類型的動態性特點足以表示所有資料。JS提供typeof操作符來檢測變數的資料類型。

(typeof返回的是字串有六種可能:"number","string","boolean","object","function","undefined")。

    我們先來看看Undefined這個資料類型吧,Undefined類型只有一個特殊的值——undefined。undefined表示"缺少值",就是此處應該有一個值,但是還沒有定義。典型用法是:

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

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

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

   (4)函數沒有傳回值時,預設返回undefined。

    例如:

              var color;

              alert(message == undefined);//true

    這個例子只聲明了變數color,但未對其初始化。比較這個變數與undefined字面量,結果表明它們是相等的。這個例子與下面的例子是等價的:

              var color = undefined;

              alert(color == undefined)  ;//true

    不過,包含undefined值的變數與尚未定義的變數還是不一樣的:

             var color ;//變數聲明之後預設取得undefined值

              //未聲明的變數

              //var age

              alert(color);   //"undefined"

              alert(age);    //產生錯誤

    然而,對未初始化的變數執行typeof操作符會返回undefined值,而對未聲明的變數執行typeof操作符同樣也會返回undefined值。

              var color;//變數聲明之後預設取得undefined值

                 //未聲明的變數

              //var age

              alert(typeof color);  //"undefined"

              alert(typeof age);   // "undefined"

   結果表明,對未初始化和未聲明的變數執行 typeof 操作符都返回了 undefined 值;這個結果有其邏輯上的合理性。因為雖然這兩種變數從技術角度看有本質區別,但實際上無論對哪種變數也不可能執行真正的操作。

 

    歡迎關注公眾號:wcs290130——JavaScript那些事兒

JS中六種資料類型(一)——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.