map和forEach区别

forEach

在es5中提供了forEach方法进行遍历,其实就是模仿了jQuery中each方法,不过将 i 于v进行了调换,下面两种方法进行对比一下,forEach本身不会返回任何值(undefined)
var arr = [ 11, 22, 33 ,44,55];
var res = $.each( arr, function ( i, v ) {

console.log( i + ', ' + v );
return false/true;//判断循环是否结束

});
console.log( res ); // 返回遍历的数组

var res = arr.forEach(function ( v, i ) {

console.log( i + ', ' + v );
return true;

});
console.log( res ); // 返回遍历的数组

map

map也是循环遍历数组的语法,默认返回一个数组[undefined,undefined,...(数组的length)]
var arr = [ 11, 22, 33 ,44];
var res = arr.map( function ( v, i) {

console.log( i + ', ' + v );
return v * 2;

});
console.log( res );//返回新数据

评论

暂无评论