for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
// 遍历second,将非undefined的值添加到first中
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
// 修正first的length属性,因为first可能不是真正的数组
first.length = i;
return first;
},
// 过滤数组,返回新数组;callback返回true时保留;如果inv为true,callback返回false才会保留
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
// 遍历数组,只保留通过验证函数callback的元素
for ( var i = 0, length = elems.length; i < length; i++ ) {
// 这里callback的参数列表为:value, index,与each的习惯一致
retVal = !!callback( elems[ i ], i );
// 是否反向选择
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
// 将数组或对象elems的元素/属性,转化成新的数组
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
// 检测elems是否是(伪)数组
// 1. 将jQuery对象也当成数组处理
// 2. 检测length属性是否存在,length等于0,或第一个和最后一个元素是否存在,或jQuery.isArray返回true
isArray = elems instanceof jQuery
|| length !== undefined && typeof length === “number”
&& ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// 是数组或对象的差别,仅仅是遍历的方式不同,没有其他的区别
// Go through the array, translating each of the items to their
// 遍历数组,对每一个元素调用callback,将返回值不为null的值,存入ret
if ( isArray ) {
for ( ; i < length; i++ ) {
// 执行callback,参数依次为value, index, arg
value = callback( elems[ i ], i, arg );
// 如果返回null,则忽略(无返回值的function会返回undefined)
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
// 遍历对象,对每一个属性调用callback,将返回值不为null的值,存入ret
} else {
for ( key in elems ) {
// 执行callback,参数依次为value, key, arg
value = callback( elems[ key ], key, arg );
// 同上
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
// 使嵌套数组变平
// concat:
// 如果某一项为数组,那么添加其内容到末尾。
// 如果该项目不是数组,就将其作为单个的数组元素添加到数组的末尾。
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,










