jquery的makeArray 函數可以將一個類別數組物件轉成數組,官方API解釋和測試範例在這裡(#Convert an array-like object into a true JavaScript array.)那麼什麼是類別陣列物件呢? ( array-like object ) 這是Arrary-Like的定義
Either a true JavaScript Array or a JavaScript Object that contains a nonnegative integer length
property
and index properties from 0
up to length
- 1
. This latter case includes array-like objects commonly encountered in web-based code such as the arguments
object
and the NodeList
object returned by many DOM methods.
When a jQuery API accepts either plain Objects or Array-Like objects, a plain Object with a numeric .
will trigger the Array-Like behavior.含有length屬性,且值不為負數,能夠依照下標存取屬性。常見的類別數組物件有aruments,NodeList
// results is for internal usage only result是jquery内部使用的参数,如果不为空则把array并到resuls上 makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); //array没有length属性,或者为string类型,function类型,window类型,或者黑莓中正则对象,黑莓中正则对象也含有length对象,则push到result if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { //调用merge把类数组array合并到ret jQuery.merge( ret, array ); } } return ret; }
jquery.isWindow() 1.7.1是根據是否包含setInterval屬性來判斷的"setInterval" in obj,而以後版面是透過window屬性來判斷的obj == obj.window
isWindow:function(obj){ return obj && typeof obj === "object" && "setInterval" in obj; //1.7.2: return obj != null && obj == obj.window; },
merge: function( first, second ) { var i = first.length, j = 0; //length属性为数字,则把second当做数组处理,没有length属性或者不为数字当做含有连续整型的属性对象处理{0:"HK",1:"CA"} if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { //把不为undefined的都合并到first中 first[ i++ ] = second[ j++ ]; } } first.length = i; //修正length属性,fisrt可能不为真正的数组类型 return first; },
以上是jQuery中.makeArray()的程式碼閱讀的詳細內容。更多資訊請關注PHP中文網其他相關文章!