利用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 );
}