我知道有很多这样的话题。我知道基本原理:. 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返回一个新数组。

forEach没有返回值。

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

其他回答

.map和. foreach会做同样的事情,直到你开始对拥有数百万个元素的数组进行操作。.map会创建另一个具有相同大小(可能还有类型,这取决于数组的种类)的集合,这可能会占用大量内存。

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

arr.map()

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

arr.forEach()

返回未定义。

性能分析 随着数组中元素数量的增加,For循环比map或foreach执行得更快。

Let array = []; For (var I = 0;I < 20000000;我+ +){ array.push(我) } console.time(“映射”); 数组中。映射(num => { 返回num * 4; }); console.timeEnd(“映射”); console.time (' forEach '); 数组中。forEach((num, index) => { 返回数组[index] = num * 4; }); console.timeEnd (' forEach '); console.time(“的”); For (i = 0;I < array.length;我+ +){ 数组[i] =数组[i] * 2; } console.timeEnd(“的”);

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

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

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