相同点:
-
都是循环遍历数组中的每一项
-
每次执行匿名函数都支持三个参数,参数分别为item(当前每一项),index(索引值),arr(原数组)
-
匿名函数中的this都是指向window
-
只能遍历数组
不同点:
map()
map方法返回一个新的数组,数组中的元素为原始数组调用函数处理后的值
也就是map()进行处理之后返回一个新的数组
⚠️注意:map()方法不会对空数组进行检测
map方法不会改变原始数组
forEach
forEach方法用于调用数组的每个元素,将元素传给回调函数
⚠️注意: forEach对于空数组是不会调用回调函数的 ,
没有返回一个新数组&没有返回值
var arr = [1, 2, 3, 4, 5]
// arr.map(...)会有一个新的数组返回
arr.map(function(element, index, array) {
return element * 2;
})
// (5) [2, 4, 6, 8, 10]
// arr.forEach() 只是对遍历的每个元素做一些操作(如输出)
arr.forEach(function(element, index, array) {
console.log(element * 2)
})
// 2
// 4
// 6
// 8
// 10