1 相同点
- 都是ES5的规范
- 不会直接改变原数组
- callback函数值有三个参数:currentVaule、index、array,另外一个参数可以指定当前调用对象thisArg
2 不同点
- forEach返回undefined,并且不可链式调用;map返回一个新数组
- 没有办法终止或者跳出forEach()循环,除非抛出异常,所以想执行一个数组是否满足什么条件,返回布尔值,可以用一般的for循环实现,或者用Array.every()或者Array.some();
3 栗子
定义一个数组:
var arr = [1, 2, 3, 4];
注意下面的示例代码每次操作前都是先将arr还原成[1, 2, 3, 4]再看结果的
- 返回值
var eachRes = arr.forEach(function(currentValue, index, arr) {
return currentValue + 1;
});
var mapRes = arr.map(function(currentValue, index, arr) {
return currentValue + 1;
});
console.log(eachRes); //undefined
console.log(mapRes); //[2, 3, 4, 5]
console.log(arr); //[1, 2, 3, 4]
- 修改原数组
//forEach
arr.forEach(function(currentValue, index, arr) {
if(currentValue === 2) {
arr.pop();
}
});
console.log(arr); //[1, 2, 3]
//map
arr.map(function(currentValue, index, arr) {
if(currentValue === 2) {
arr.pop();
}
});
console.log(arr); //[1, 2, 3]
- 一个笔试题
['1', '2', '3', '4'].map(parseInt); // [1, NaN, NaN, NaN]
这主要是因为 parseInt()默认有两个参数,第二个参数是进制数。当parsrInt没有传入参数的时候,而map()中的回调函数时候,会给它传三个参数,第二个参数就是索引,明显不正确,所以返回NaN了。详见JavaScript parseInt用法
function returnInt(element){
return parseInt(element,10);
}
['1', '2', '3', '4'].map(returnInt);
// [1, 2, 3, 4]