js 判斷各種資料類型的簡單方法(推薦),js資料類型

來源:互聯網
上載者:User

js 判斷各種資料類型的簡單方法(推薦),js資料類型

瞭解js的都知道, 有個typeof  用來判斷各種資料類型,有兩種寫法:typeof   xxx   ,typeof(xxx)

 如下執行個體:

typeof   2      輸出   number

typeof   null   輸出   object

typeof   {}    輸出   object

typeof    []    輸出   object

typeof   (function(){})   輸出  function

typeof    undefined  輸出  undefined

typeof   '222'   輸出    string

typeof  true     輸出     boolean

這裡麵包含了js裡面的五種資料類型  number   string    boolean   undefinedobject和函數類型 function

看到這裡你肯定會問了:我怎麼去區分對象,數組和null呢?

接下來我們就用到另外一個利器: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]

看到這裡,剛才的問題我們解決了。

其實js 裡面還有好多類型判斷 

[object HTMLDivElement]   div 對象 ,   
[object HTMLBodyElement]  body 對象,
[object Document](IE)或者 
[object HTMLDocument](firefox,google) ......

各種dom節點的判斷,這些東西在我們寫外掛程式的時候都會用到。

可以封裝的方法如下:

var  gettype=Object.prototype.toStringvar  utility={isObj:function(o){    return  gettype.call(o)=="[object Object]"; },     isArray:function(o){        return  gettype.call(o)=="[object Array]";     },     isNULL:function(o){        return  gettype.call(o)=="[object Null]";     },     isDocument:function(){        return  gettype.call(o)=="[object Document]"|| [object HTMLDocument];     }     ........}

以上這篇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.