Array: forEach 和 map 有什么不同?

342 阅读2分钟

forEch

定义

forEach 对数组的每个元素执行一次指定函数

语法

Array.forEach(callback(currentValue, index, array){})

参数

callback: 即定义指出的执行一次给定函数 , callback 接受1-3个参数

  1. currentValue: 数组中正在处理的当前元素,必选
  2. index: 数组中正在处理的当前元素的索引,可选
  3. array: forEach操作的当前数组,可选

thisArg:执行callback时指定的this对象

返回值

undefined, forEach 的返回值永远为undefined

实例解析

const arr = [1, 2, 3, 5, 4];
const obj = {a: 'a'};

const res = arr.forEach(function(value, index, arr) {
    console.log(value, index, arr, this.a)}, obj);

console.log(res)

输出结果:
1 0 [ 1, 2, 3, 5, 4 ] 'a'
2 1 [ 1, 2, 3, 5, 4 ] 'a'
3 2 [ 1, 2, 3, 5, 4 ] 'a'
5 3 [ 1, 2, 3, 5, 4 ] 'a'
4 4 [ 1, 2, 3, 5, 4 ] 'a'
undefined

Note

forEach 可以在callback中改变原数组

map

定义

map 创建一个新数组,该数组中的每个元素是调用一次指定函数的返回值。

语法

const newArray = Array.forEach(callback(currentValue, index, array){})

参数

callback: 即定义指出的执行一次给定函数 , callback 接受1-3个参数

  1. currentValue: 数组中正在处理的当前元素,必选
  2. index: 数组中正在处理的当前元素的索引,可选
  3. array: map操作的当前数组,可选

thisArg:执行callback时指定的this对象

返回值

数组 由原数组每个元素执行回调函数的结果组成的新数组

实例解析

const arr = [1, 2, 3, 5, 4];
const obj = {a: 'a'};

const res = arr.map(function(value, index, arr){
    console.log(value, index, arr, this.a);    
    return value > 2 && value || 0;
}, obj);

console.log(res);

输出结果:
1 0 [ 1, 2, 3, 5, 4 ] 'a'
2 1 [ 1, 2, 3, 5, 4 ] 'a'
3 2 [ 1, 2, 3, 5, 4 ] 'a'
5 3 [ 1, 2, 3, 5, 4 ] 'a'
4 4 [ 1, 2, 3, 5, 4 ] 'a'
[ 0, 0, 3, 5, 4 ]

Note

map 遍历数组时,每次都会返回一个值,如果没有显示返回,就返回 undefined

总结

map 和 forEach 的主要区别是有无返回值。forEach 返回值永远为undefined, map 则返回一个新数组。所以,当你想基于一个原数组返回一个新数组,可以选择 map,当你只是想遍历数据不需要考虑返回时可以选择 forEach。

如果有问题或者描述不清的朋友们,欢迎留言一起探讨,如果本文有给你们帮助请帮忙点个赞。