我知道有很多这样的话题。我知道基本原理:. 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。 如果这是一个愚蠢的问题,我很抱歉,但我对这门语言很陌生,到目前为止我找到的答案并不能让我满意。


当前回答

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“创建一个新数组,其中包含对该数组中的每个元素调用所提供的函数的结果。”

forEach实际上不返回任何东西。它只是为每个数组元素调用函数,然后就完成了。所以无论你在被调用的函数中返回什么都会被丢弃。

另一方面,map将类似地为每个数组元素调用函数,但它不会丢弃它的返回值,而是捕获它并构建一个包含这些返回值的新数组。

这也意味着你可以在使用forEach的任何地方使用map,但你仍然不应该这样做,这样你就不会毫无目的地收集返回值。如果你不需要它们,不收集它们会更有效率。

性能分析(同样-不是很科学) 根据我的经验,有时候.map()比.foreach()更快。

let rows = []; for (let i = 0; i < 10000000; i++) { // console.log("here", i) rows.push({ id: i, title: 'ciao' }); } const now1 = Date.now(); rows.forEach(row => { if (!row.event_title) { row.event_title = `no title ${row.event_type}`; } }); const now2 = Date.now(); rows = rows.map(row => { if (!row.event_title) { row.event_title = `no title ${row.event_type}`; } return row; }); const now3 = Date.now(); const time1 = now2 - now1; const time2 = now3 - now2; console.log('forEach time', time1); console.log('.map time', time2);

在我的macbook pro上(2013年底)

在1909年 .map时间444

Map隐式返回,而forEach不返回。

这就是为什么当你在编写JSX应用程序时,你几乎总是使用map而不是forEach来在React中显示内容。

Map返回一个新数组。

forEach没有返回值。

这就是区别的核心。这里的大多数其他答案都有效地说明了这一点,但以一种更复杂的方式。