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

2018-10-11  本文已影响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: 为数组中每个元素执行的函数,该函数接收三个参数:

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

Array.prototype.map()

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

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

不同点

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

返回值:undefined

Array.prototype.map()

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

建议

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

上一篇 下一篇

猜你喜欢

热点阅读