我知道有很多这样的话题。我知道基本原理:. foreach()操作原始数组,.map()操作新数组。

在我的例子中:

function practice (i){
    return i+1;
};

var a = [ -1, 0, 1, 2, 3, 4, 5 ];
var b = [ 0 ];
var c = [ 0 ];
console.log(a);
b = a.forEach(practice);
console.log("=====");
console.log(a);
console.log(b);
c = a.map(practice);
console.log("=====");
console.log(a);
console.log(c);

这是输出:

[ -1, 0, 1, 2, 3, 4, 5 ]
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
undefined
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
[ 0, 1, 2, 3, 4, 5, 6 ]

我不明白为什么使用practice会改变b的值为undefined。 如果这是一个愚蠢的问题,我很抱歉,但我对这门语言很陌生,到目前为止我找到的答案并不能让我满意。


当前回答

需要指出的一点是,这两个方法都跳过未初始化的值,但map将它们保留在返回的数组中。

var arr = [1, , 3];

arr.forEach(function(element) {
    console.log(element);
});
//Expected output: 1 3

console.log(arr.map(element => element));
//Expected output: [1, undefined, 3];

其他回答

forEach()和map()的区别

forEach()只是循环遍历元素。它会丢弃返回值并且总是返回undefined。此方法的结果不提供输出。

Map()循环遍历元素,通过迭代主数组分配内存并存储返回值

例子:

   var numbers = [2,3,5,7];

   var forEachNum = numbers.forEach(function(number){
      return number
   })
   console.log(forEachNum)
   //output undefined

   var mapNum = numbers.map(function(number){
      return number
   })
   console.log(mapNum)
   //output [2,3,5,7]

map()比forEach()快

const arr = [...Array(100000000).keys()];

console.time("for");
for (let i = 0; i < arr.length; i++) {}
console.timeEnd("for");

console.time("while");
let j = 0;
while (j < arr.length) {
  j++;
}
console.timeEnd("while");

console.time("dowhile");
let k = 0;
do {
  k++;
} while (k < arr.length);
console.timeEnd("dowhile");

console.time("forEach");
arr.forEach((element) => {});
console.timeEnd("forEach");

VM35:6用于:45.998046875 ms

VM35:13 while: 154.581787109375 ms

VM35:20 dowhile: 141.97216796875 ms

VM35:24 forEach: 776.469970703125 ms

不同之处在于他们的回报。执行后:

arr.map()

返回由已处理函数生成的元素数组;而:

arr.forEach()

返回未定义。

它们不是一回事。让我来解释一下其中的区别。

forEach:它遍历一个列表,并对每个列表成员应用一些具有副作用的操作(例如:将每个列表项保存到数据库),并且不返回任何东西。

map:遍历一个列表,转换该列表的每个成员,并返回另一个与转换后的成员相同大小的列表(例如:将字符串列表转换为大写)。它不会改变被调用的数组(尽管回调函数可能会这样做)。

参考文献

Array.prototype.forEach() - JavaScript | MDN

Array.prototype.map() - JavaScript | MDN

forEach() map()
Functionality Performs given operation on each element of the array Performs given "transformation" on a "copy" of each element
Return value Returns undefined Returns new array with transformed elements, leaving back original array unchanged.
Preferrable usage scenario and example Performing non-tranformation like processing on each element.

For example, saving all elements in the database.
Obtaining array containing output of some processing done on each element of the array.

For example, obtaining array of lengths of each string in the array

forEach()例子

chars = ['Hello', 'world!!'); var retVal = char . foreach(函数(字){ console.log(" save to db: " + word) }) console.log (retVal) / /定义

map()例子

chars = ['Hello', 'world!!'); Var长度= char .map(函数(单词){ 返回word.length }) console.log(长度)/ /(5、8)