map和forEach的区别
共同点:
-
都是遍历数组的方法
-
每次执行匿名函数都支持三个参数,参数分别为item(当前每一项),index(索引值),arr(原数组)
不同点:
- map操作不会改变原数组,会存储新数组并返回
- forEach会改变原数组,没有返回值
forEach
var arr1 = [0,2,4,6,8];
var newArr1 = arr1.forEach(function(item,index,arr1){
console.log(arr1);
arr1[index] = item/2; //每次遍历,对应的值改变
},this);//没有返回值
console.log(arr1);
console.log(newArr1);
结果
map
var arr = [0,2,4,6,8];
var newArr = arr.map(function(item,index,arr){
console.log(arr);
return item/2;//有返回值
},this);
console.log(arr);//始终不变 [ 0, 2, 4, 6, 8 ]
console.log(newArr);//[ 0, 1, 2, 3, 4 ]
结果
总结:map相当于把原数组克隆一份进行修改,forEach直接在原数组上修改