美文网首页
forEach() 方法 和 map() 方法对比

forEach() 方法 和 map() 方法对比

作者: 林键燃 | 来源:发表于2018-10-11 16:44 被阅读2次

相同点

语法相同
Array.prototype.forEach()
arr.forEach(function callback(currentValue[, index[, array]]) {
    //your iterator
}[, thisArg]);
Array.prototype.map()
let new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])
参数相同
Array.prototype.forEach()

callback: 为数组中每个元素执行的函数,该函数接收三个参数:

  • currentValue: 数组中正在处理的当前元素。
  • index可选: 数组中正在处理的当前元素的索引。
  • array可选: forEach()方法正在操作的数组。

thisArg可选: 可选参数。当执行回调 函数时用作this的值(参考对象)。

Array.prototype.map()

callback: 为数组中每个元素执行的函数,该函数接收三个参数:

  • currentValue: 数组中正在处理的当前元素。
  • index可选: 数组中正在处理的当前元素的索引。
  • array可选: map()方法正在操作的数组。

thisArg可选: 可选参数。当执行回调 函数时用作this的值(参考对象)。

不同点

返回值不同
Array.prototype.forEach()

返回值:undefined

Array.prototype.map()

返回值:一个新数组,每个元素都是回调函数的结果

建议

实际使用中map()基本能代替forEach(),如果不需要return的话可以使用forEach()方法,如果需要创建新数组时使用map()方法。

相关文章

网友评论

      本文标题:forEach() 方法 和 map() 方法对比

      本文链接:https://www.haomeiwen.com/subject/flnbaftx.html