1. 定义
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
forEach() 对数组内每一个元素执行提供的函数
2. 用法
array.map(function(currentValue,index,arr), thisValue)
array.forEach(function(currentValue,index,arr), thisValue)
currentValue:必选 当前元素值
index:可选 当前元素索引
arr:可选 当前数组对象
3. 例子
let arr1 = [1,2,3,4]
let newArr = arr1.map((item) => {
return item * item
})
console.log(arr1)//[1,2,3,4]
console.log(newArr)//[1,4,9,16]
let arr2 = [1,2,3,4]
arr2.forEach((item) => {
item * item
})
console.log(arr2)//[1,4,9,16]
基本用法是一样的。但是map函数有返回值,返回的是对数组执行操作后的数组,不会改变原数组。
而forEach函数没有返回值,直接在原数组上执行操作函数,会改变原数组。