利用Object.toString.call()方法
看代碼
先初始化class2type,將每種對象的toString后的值和type建立對應關系
core_toString.call([])輸出"[Object Array]"
class2type = {} core_toString = class2type.toString // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); });
type方法
type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }
雖然不需要typeof也可以用class2type判斷,但並不是都通過class2type判斷,只有object和function才通過class2type判斷對象的類型,其他對象還是通過typeof判斷。
從對象中查找更從數組中查找一樣,每次都要去循環,typeof不需要循環查找,更快一些
是否是數值,並不通過 typeof判斷,isNumeric方法
isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }