你不知道的JavaScript——類型

來源:互聯網
上載者:User

標籤:string   none   rip   檢測   fine   type   log   typeof   其他   

一、ECMAScript語言中所有的值均有一個對應的語言類型。ECMAScript語言類型包括Undefined、Null、Boolean、String、Number和Object。

  我們這樣來定義類型:對於語言引擎和開發人員來說,類型是值的內部特徵,它定義了值的行為,以使其區別於其它值。

  JS有七種內建類型:

  • 空值(null)
  • 未定義(undefined)
  • 布爾值(boolean)
  • 數字(number)
  • 字串(string)
  • 對象(object)
  • 符號(symbol,ES6中新增)

  注意:除了對象外,其他統稱為“基本類型”。

  我們可以用typeof運算子來查看值的類型,它返回的是類型的字串值。例如:

      1. typeof undefined   ===  "undefined";
      2. typeof true             ===  "boolean";
      3. typeof 42                    ===        "number";
      4. typeof "42"                 ===         "string";
      5. typeof { life:42 }          ===         "object";
      6. typeof Symbol             ===         "symbol";     //ES6中新加入的類型

  但是 typeof null === "object";   這個是js的一個bug,由來已久(20多年了)。

  那麼我們需要符合條件來檢測null值的類型

var a=null;(!a&&typeof a==="object");  //true

  函數是“可調用對象”,實際上function(函數)是object的一個“子類型”,它有一個內部屬性[[Call]],該屬性使其可以被調用。

  typeof function a(){ /**/ } ==="function";   //true

     函數不僅是對象,還可以擁有屬性。例如:

  

function a(b,c){    /*...*/}//函數對象的length屬性是其聲明的參數的個數,那麼:a.length;//2

  無專屬偶,數組也是object的一個“子類型”,數組的元素按數字來進行索引(而非普通像對象那樣通過字串索引值對),其length屬性是元素的個數。

  typeof [1,2,3] ==="object";  //true

 二、值和類型

  JavaScript中的變數是沒有類型的,只有值才有。變數可以隨時持有任何類型的值。也就是說語言引擎不要求變數總是持有與其初始值同類型的值。

  

var a=42;typeof a;    //"number"a=true;typeof a;    //"boolean"typeof typeof 42    //"string"//typeof 42 首先返回字串“number”,然後typeof “number” 返回 “string”

  undefined和undeclared完全是兩回事。

變數在未持有值的時候為undefined。此時typeof 返回“undefined”:

首先看下undefined

var a;typeof a;    //"undefined"var b=42;var c;//laterb=c;typeof b;    //"undefined"typeof c;    //"undefined"

 undefined和undeclared的區別:

var a;a;  //fundefinedb;  //ReferenceError: b is not defined   其實這裡的意思是:b is not declared 可是sb瀏覽器不會說那麼清楚,我們需要原諒它。//然而更讓人抓狂的是 typeof 處理undeclared變數的方式。例如:var a;typeof a;  //"undefined"typeof b;  //"undefined"   而且這裡沒有報錯,是因為typeof 有一個特殊的安全防範機制,這裡typeof如果能返回undeclared而非undefined的話,多好啊,可惜sb瀏覽器不會!

 

你不知道的JavaScript——類型

聯繫我們

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