js辨別對象的類型

來源:互聯網
上載者:User

標籤:target   logs   適用於   reg   函數   cti   strong   支援   html   

本文主要針對 Null,ExpReg,Array,Date這一些typeof函數辨別不了的對象; 

順便貼上一篇關於typeof的理解:http://www.cnblogs.com/chaky/p/7284163.html

 

首先,辨別物件類型的方法:

1、instanceof(是否...的執行個體)  返回true or false

  我們可以用它來辨別 ExpReg Array Date類型的對象  不適用於null

  

 

2、constructor //原型對象裡的構造器指向; 不支援null識別

  

 這裡有一處不解的是:

  Object指向構造器是Function

  而他原型裡的construction指向的是 叫Object的建構函式

 

 

3、isArray 專門用於數組識別 (Array對象特有方法,不被子例 ‘繼承‘ );

   

 

4、String() 區分null 和 undefined  //該函數底層實現應有全等比較符

  

 

5、根據物件類型特性判斷屬於是哪種對象;

  有3種類型 Array String NodeList;

  其中他們都有 length屬性;

  forEach只有 Array和NodeList有;

  Array有concat,NodeList沒有 

  通過特性的辨別我們就可以區分出3種屬性類型;

 

6、萬用辨別類型的方法,原理是通過 toString這方法;//轉載,非原創

var is =   function (obj,type) { 

      return (type === "Null" && obj === null) || 

           (type === "Undefined" && obj === void 0 ) || 

           (type === "Number" && isFinite(obj)) || Object.prototype.toString.call(obj).slice(8,-1) === type; 

}

 

 ------------------------如果有更好的辨別方法歡迎留言!--------------------------

  

  

  

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.