DIV CSS 佈局教程網

JS 型別判斷入門:typeof 與 Object.prototype.toString
編輯:關於JavaScript     

寫過 JS 的人都知道有個 typeof 可以用來判斷資料型別,它有兩種寫法:typeof xxx 與 typeof(xxx)。

先看 typeof 的實際輸出

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、undefined,加上 object 與 function。看到這裡你大概會想問:那我要怎麼把物件、陣列和 null 分開?

換用 Object.prototype.toString.call

這是 Object 原型上的原生方法,能給出更精確的型別標籤:

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]

剛才那個問題就這樣解決了。它甚至能再往下細分 DOM 節點:

[object HTMLDivElement]   div 對象 ,   

[object HTMLBodyElement]  body 對象,

[object Document](IE)或者 [object HTMLDocument](Firefox、Chrome)……

這些判斷在寫外掛的時候經常用得上。

封裝成工具函式

 var gettype=Object.prototype.toString var 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]; } ........ }

實務上要注意的是,跨 iframe 或跨執行環境時物件的原型可能不同,這時 Array.isArray() 會比比對標籤字串更可靠;兩者搭配使用,基本能應付絕大多數的型別判斷需求。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved