JavaScript:.forEach() 和 .map() 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34426458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:19:15  来源:igfitidea点击:

JavaScript: Difference between .forEach() and .map()

javascriptarraysloopsforeach

提问by DzikiChrzan

I know that there were a lot of topics like this. And I know the basics: .forEach()operates on original array and .map()on the new one.

我知道有很多这样的话题。而且我知道基础知识:.forEach()对原始数组和.map()新数组进行操作。

In my case:

就我而言:

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);

And this is output:

这是输出:

[ -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 ]

I can't understand why using practicechanges value of bto undefined.
I'm sorry if this is silly question, but I'm quite new in this language and answers I found so far didn't satisfy me.

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

回答by Richard Hamilton

They are not one and the same. Let me explain the difference.

他们不是一回事。让我解释一下区别。

forEach: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database)

forEach:这会遍历一个列表,并对每个列表成员应用一些具有副作用的操作(例如:将每个列表项保存到数据库中)

map: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase)

map:这将迭代一个列表,转换该列表的每个成员,并返回另一个与转换成员大小相同的列表(例如:将字符串列表转换为大写)

References

参考

Array.prototype.forEach() - JavaScript | MDN

Array.prototype.forEach() - JavaScript | MDN

Array.prototype.map() - JavaScript | MDN

Array.prototype.map() - JavaScript | MDN

回答by poke

  • Array.forEach“executes a provided function once per array element.”

  • Array.map“creates a new array with the results of calling a provided function on every element in this array.”

  • Array.forEach“每个数组元素执行一次提供的函数。”

  • Array.map“创建一个新数组,其结果是对该数组中的每个元素调用提供的函数。”

So, forEachdoesn't actually return anything. It just calls the function for each array element and then it's done. So whatever you return within that called function is simply discarded.

所以,forEach实际上并没有返回任何东西。它只是为每个数组元素调用函数,然后就完成了。因此,您在该被调用函数中返回的任何内容都将被简单地丢弃。

On the other hand, mapwill similarly call the function for each array element but instead of discarding its return value, it will capture it and build a new array of those return values.

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

This also means that you coulduse mapwherever you are using forEachbut you still shouldn't do that so you don't collect the return values without any purpose. It's just more efficient to not collect them if you don't need them.

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

回答by Mahesha999

+----------------+-------------------------------------+---------------------------------------+
|                | foreach                             | map                                   |
+----------------+-------------------------------------+---------------------------------------+
| Functionality  | Performs given operation on each    | Performs given "transformation" on    |
|                | element of the array                | "copy" of each element                |
+----------------+-------------------------------------+---------------------------------------+
| Return value   | Returns undefined                   | Returns new array with tranformed     |
|                |                                     | elements leaving back original array  |
|                |                                     | unchanged                             |
+----------------+-------------------------------------+---------------------------------------+
| Preferrable    | Performing non-transformation like  | Obtaining array containing output of  |
| usage scenario | processing on each element.         | some processing done on each element  |
| and example    |                                     | of the array.                         |
|                | For example, saving all elements in |                                       |
|                | the database                        | For example, obtaining array of       |
|                |                                     | lengths of each string in the         |
|                |                                     | array                                 |
+----------------+-------------------------------------+---------------------------------------+

回答by Rahul Desai

The main difference that you need to know is .map()returns a new array while .forEach()doesn't. That is why you see that difference in the output. .forEach()just operates on every value in the array.

您需要知道的主要区别是.map()返回一个新数组,.forEach()而不返回。这就是为什么您会在输出中看到这种差异。.forEach()只对数组中的每个值进行操作。

Read up:

阅读:

You might also want to check out: - Array.prototype.every()- JavaScript | MDN

您可能还想查看: - Array.prototype.every()- JavaScript | MDN

回答by Amarnath Jeyakumar

forEach: If you want to perform an action on the elements of an Array and it is same as you use for loop. The result of this method does not give us an output buy just loop through the elements.

forEach:如果要对数组的元素执行操作,则与使用 for 循环相同。这种方法的结果不会给我们一个输出,只是循环遍历元素。

map: If you want to perform an action on the elements of an array and also you want to store the output of your action into an Array. This is similar to for loop within a function that returns the result after each iteration.

map:如果你想对数组的元素执行一个操作,并且你想将你的操作的输出存储到一个数组中。这类似于在每次迭代后返回结果的函数中的 for 循环。

Hope this helps.

希望这可以帮助。

回答by Godwin Ekuma

The difference lies in what they return. After execution:

不同之处在于它们返回的内容。执行后:

arr.map()

returns an array of elements resulting from the processed function; while:

返回由处理函数产生的元素数组;尽管:

arr.forEach()

returns undefined.

返回未定义。

回答by sonia kaushal

Performance AnalysisFor loops performs faster than map or foreach as number of elements in a array increases.

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

let array = [];
for (var i = 0; i < 20000000; i++) {
  array.push(i)
}

console.time('map');
array.map(num => {
  return num * 4;
});
console.timeEnd('map');


console.time('forEach');
array.forEach((num, index) => {
  return array[index] = num * 4;
});
console.timeEnd('forEach');

console.time('for');
for (i = 0; i < array.length; i++) {
  array[i] = array[i] * 2;

}
console.timeEnd('for');

回答by Conny Olsson

One thing to point out is that foreach skips uninitialized values while map does not.

需要指出的一件事是 foreach 会跳过未初始化的值,而 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];

回答by Prakash Harvani

Diffrence between Foreach & map :

Foreach 和 map 的区别:

Map(): If you use map then map can return new array by iterating main array.

Map():如果您使用 map 则 map 可以通过迭代主数组来返回新数组。

Foreach(): If you use Foreach then it can not return anything for each can iterating main array.

Foreach():如果你使用 Foreach 那么它不能为每个可以迭代的主数组返回任何东西。

useFul link: use this link for understanding diffrence

useFul 链接:使用此链接了解差异

https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

回答by Neethan Badea

Map implicitly returns while forEach does not.

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

This is why when you're coding a JSX application, you almost always use map instead of forEach to display content in React.

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