1.typeof
type of ...判斷數據類型
number返回number
string返回string
boolean返回boolean
undefined返回undefined
null返回object
function返回function
object返回object
array返回object
NAN返回number
2.instanceof
檢查某對象是否屬於某類型
instanceof是通過原型鏈來檢查類型的,所以適用於任何”object”的類型檢查。
3.toString
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]
4. constructor也能判斷數據類型:
如:
''.constructor==String [].constructor==Array var obj= new Object() obj.constructor==Object
檢查所有數據類型的方法
function checkType (obj) { return Object.prototype.toString.call(obj).slice(8,-1) }
類型檢測總結
==typeof==只能檢測基本數據類型,對於null還有Bug;
==instanceof==適用於檢測對象,它是基於原型鏈運作的;
==constructor==指向的是最初創建者,而且容易偽造,不適合做類型判斷;
==Object.prototype.toString==適用於ECMA內置JavaScript類型(包括基本數據類型和內置對象)的類型判斷;
基於引用判等的類型檢查都有跨窗口問題,比如instanceof和constructor。
總之,如果你要判斷的是基本數據類型或JavaScript內置對象,使用toString; 如果要判斷的時自定義類型,請使用instanceof。