js 中關於資料類型的判斷

來源:互聯網
上載者:User

標籤:[]   使用   string   節點   cti   函數   firefox   box   htm   

1.輕量級typeof

typeof 通常能判斷以下6種資料類型,在平時開發中使用率比較高,存在的缺點是不夠精準。比如typeof 對 array ,null,{}的判斷均輸出了Object。

  • "number"
  • "string"
  • "boolean"
  • "object"
  • "function"
  • "undefined"  

2.我們來討論下另一個種方式:Object.prototype.toString.call,這是對象的一個原生原型擴充函數,用來更精確的區分資料類型。

  var   getType=Object.prototype.toString;

  getType.call(‘aaaa‘)        輸出      [object String]

      getType.call(2222)         輸出      [object Number]

      getType.call(true)          輸出      [object Boolean]

      getType.call(undefined)  輸出      [object Undefined]

      getType.call(null)                  輸出   [object Null]

      getType.call({})                   輸出   [object Object]

      getType.call([])                    輸出   [object Array]
      getType.call(function(){})     輸出   [object Function]

還有[object Document](IE)或者  [object HTMLDocument](firefox,google)等dom節點的判斷

js 中關於資料類型的判斷

聯繫我們

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