jquery判斷對象的type


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM