each/map遍历方法封装
1.each方法
function each( obj, callback ) {
var length, i = 0;
//isArrayLike前期有封装,直接拿来用就行了
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
}
each([1,2,3], function(item, index){
console.log(item, index)//1 0; 2 1; 3 2
//逻辑代码
})
2.map方法
function map( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return Array.prototype.concat.apply( [], ret );
}
//map方法会返回一个新的数组
总结:
each/map方法方便之处就是数组/对象都可以遍历处理