forEach()和map()两个方法都是与for循环一样,其作用与for循环功能相似,但是没有办法终止或者跳出循环;
定义:
map() (https://www.runoob.com/jsref/jsref-map.html)
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
语法:
array.map(function(currentValue,index,arr), thisValue)
参数说明:
forEach() (https://www.runoob.com/jsref/jsref-foreach.html)
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
语法与参数与map()相同;
先来看两者之间的执行
let arr = ["a", "b", "c", "d", "e"];
arr.forEach((item, index, arr) => {
console.log(item, index, arr);
});
arr.map((item,index,arr)=>{
console.log(item,index,arr)
})
运行之后,可以看出两者参数没有任何的区别,当然他们也不能停止里面的循环遍历,
forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:前项item,索引index,原始数组arr。
我们来看看他们报错的时候各自的返回值;
let arr = ["a", "b", "c", "d", "e"];
let nums1 = arr.forEach((item, index, arr) => {
return item;
});
let nums2 = arr.map((item, index, arr) => {
return item;
});
console.log('nums1',nums1); // => undefined
console.log('nums2',nums2); // => ["a", "b", "c", "d", "e"]
上述代码可以看出;两个执行速度有些差别且:
forEach()返回值是undefined。
map()返回一个新数组,原数组不会改变。
区别:
从上述代码可以看出来:
forEach()方法不会返回执行结果,而是undefined。forEach()会修改原来的数组。
map()方法会得到一个新的数组并返回。且他们两个执行速度:forEach() < map()
使用场景:
foreach() 适合并不打算改变数据的时候使用,如:存入数据库,打印,深copy;
map() 改变数据值的时候。因为它更快,且返回一个新的数组。