isArraylike
isArraylike在jquery源码中用来判断参数是否为类数组或数组。之所以称为类数组,是因为它能够像数组一样遍历,也可以通过像数组中以中括号方式获取数组中的值一样获取类数组中的值。
通常将类数组转换为数组,对其进行操作,转换方式如下
var a = {'0':'a','1':'b',length:2} //类数组
Array.prototype.slice.call(a);//[a,b]
可能的类数组:arguments、nodeList和key值为连续整数、含有length属性的json。判断方法是查看是否含有length属性。
isArraylike源码
//判断是否为类数组
function isArraylike( obj ) {
var length = "length" in obj && obj.length;
type = jQuery.type( obj );
//排除function和window中可能有length属性的情况
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
//元素节点为类数组
if ( obj.nodeType === 1 && length ) {
return true;
}
//类型为array /长度为0 /长度为number类型/第n-1个元素存在
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
merge
merge方法用来将两个数组或类数组合并为一个类数组,而且合并的过程是破坏性的,是在第一个类数组的基础上合并的数组,合并后第一个数组发生变化。
var merge = function( first, second ) {
var len = +second.length,//当seconde.length存在时 len为数值 当不存在是second.length为undefined +second.length为NaN
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
// 当len不存在时,NaN != NaN
//{'0':'a','1':'b'}形式
if ( len !== len ) {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
};
makeArray
方法jQuery.makeArray( obj )可以将一个类数组对象转换为真正的数组
var makeArray = function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
//字符串 类数组
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
//数组
push.call( ret, arr );
}
}
return ret;
};