jQuery源码分析4: jQuery.makeArray和jQuery.toArray

jQuery源码分析4: jQuery.makeArray和jQuery.toArray

var push = Array.prototype.push,

isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj; //< 判断window对象的方法
},

merge: function( first, second ) { //合并两个数组 返回第一个数组first
var i = first.length,
j = 0;

if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}

} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}

first.length = i;

return first;
},

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属性或array本身是字符串,函数或window,或正则表达式时单独处理,因为
* window, strings和functions本身也有length属性,见如下测试:
* var fun = function() {};
* alert(fun.length); //alert 0
* var str = "hello world";
* alert(str.length); //alert 11
* alert(window.length); //< alert ...
*/

if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else { //< array参数是数组时使用jQuery.merge合并两数组
jQuery.merge( ret, array );
}
}

return ret;
},

var slice = Array.prototype.slice,

toArray: function() {
return slice.call( this, 0 );
},

你可能感兴趣的:(toArray)