jquery的makeArray 函数可以将一个类数组对象转成数组,官方API解释和测试例子在这里(Convert an array-like object into a true JavaScript array.)那么什么是类数组对象呢?( array-like object ) 这是Arrary-Like的定义
Array-Like Object
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 length
property 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.type 在
这里
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;
},
调用的jQuery.merge(frist,second) 官方解释在 这里 ,该函数的作用是把第二个数组或类数组对象合并到第一个中去
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;
},