foreach 和 map
JavaScript has some handy methods which help us iterate through our arrays. The two most commonly used for iteration are Array.prototype.map()
and Array.prototype.forEach()
.
JavaScript有一些方便的方法,可以帮助我们遍历数组。 迭代中最常用的两个是Array.prototype.map()
和Array.prototype.forEach()
。
But I think that they remain a little bit unclear, especially for a beginner. Because they both do an iteration and output something. So, what is the difference?
但是我认为它们仍然不清楚,特别是对于初学者。 因为它们都进行迭代并输出某些内容。 那么区别是什么呢?
In this article, we'll look at the following:
在本文中,我们将研究以下内容:
Definitions
定义
The returning value
返回值
Ability to chain other methods
链接其他方法的能力
Mutability
变异性
Performance Speed
性能速度
Final Thoughts
最后的想法
定义 (Definitions)
The map
method receives a function as a parameter. Then it applies it on each element and returns an entirely new array populated with the results of calling the provided function.
map
方法接收一个函数作为参数。 然后将其应用于每个元素,并返回一个全新的数组,其中填充了调用提供的函数的结果。
This means that it returns a new array that contains an image of each element of the array. It will always return the same number of items.
这意味着它将返回一个新数组,其中包含该数组每个元素的图像。 它将始终返回相同数量的项目。
const myAwesomeArray = [5, 4, 3, 2, 1]
myAwesomeArray.map(x => x * x)
// >>>>>>>>>>>>>>>>> Output: [25, 16, 9, 4, 1]
Like map
, the forEach()
method receives a function as an argument and executes it once for each array element. However, instead of returning a new array like map
, it returns undefined
.
与map
一样, forEach()
方法接收一个函数作为参数,并对每个数组元素执行一次。 但是,它不会返回像map
这样的新数组,而是返回undefined
。
const myAwesomeArray = [
{ id: 1, name: "john" },
{ id: 2, name: "Ali" },
{ id: 3, name: "Mass" },
]
myAwesomeArray.forEach(element => console.log(element.name))
// >>>>>>>>> Output : john
// Ali
// Mass
1.返回值 (1. The returning value)
The first difference between map()
and forEach()
is the returning value. The forEach()
method returns undefined
and map()
returns a new array with the transformed elements. Even if they do the same job, the returning value remains different.
map()
和forEach()
之间的第一个区别是返回值。 forEach()
方法返回undefined
而map()
返回具有转换后元素的新数组。 即使他们完成相同的工作,返回值仍然不同。
const myAwesomeArray = [1, 2, 3, 4, 5]
myAwesomeArray.forEach(x => x * x)
//>>>>>>>>>>>>>return value: undefined
myAwesomeArray.map(x => x * x)
//>>>>>>>>>>>>>return value: [1, 4, 9, 16, 25]
2.能够链接其他方法 (2. Ability to chain other methods)
The second difference between these array methods is the fact that map()
is chainable. This means that you can attach reduce()
, sort()
, filter()
and so on after performing a map()
method on an array.
这些数组方法之间的第二个区别是map()
是可链接的。 这意味着您可以在数组上执行map()
方法之后,可以附加reduce()
, sort()
, filter()
等。
That's something you can't do with forEach()
because, as you might guess, it returns undefined
.
那是您无法使用forEach()
原因,因为您可能猜到了,它返回undefined
。
const myAwesomeArray = [1, 2, 3, 4, 5]
myAwesomeArray.forEach(x => x * x).reduce((total, value) => total + value)
//>>>>>>>>>>>>> Uncaught TypeError: Cannot read property 'reduce' of undefined
myAwesomeArray.map(x => x * x).reduce((total, value) => total + value)
//>>>>>>>>>>>>>return value: 55
3.可变性 (3. Mutability)
In general, the word "mutate" means change, alternate, modify or transform. And in the JavaScript world it has the same meaning.
通常,“突变”一词是指更改,替代,修改或变换。 在JavaScript世界中,它具有相同的含义。
A mutable object is an object whose state can be modified after it is created. So, what about forEach
and map
regarding mutability?
可变对象是一种对象,其状态在创建后即可修改。 那么,关于可变性的forEach
和map
呢?
Well, according to the MDN documentation:
好吧,根据MDN文档 :
forEach()
does not mutate the array on which it is called. (However, callback
may do so).
forEach()
不会使调用它的数组发生变化。 (但是, callback
可能会这样做)。
map()
does not mutate the array on which it is called (although callback
, if invoked, may do so).
map()
不会使调用它的数组发生变化(尽管callback
,如果被调用,可能会发生变化)。
JavaScript is weird.
JavaScript很奇怪 。
Here, we see a very similar definition, and we all know that they both receive a callback
as an argument. So, which one relies on immutability?
在这里,我们看到了非常相似的定义,并且我们都知道它们都接收到callback
作为参数。 那么,哪一个依赖于不变性?
Well, in my opinion, this definition is not clear though. And to know which does not mutate the original array, we first have to check how these two methods work.
好吧,在我看来,这个定义还不清楚。 为了知道哪个不会改变原始数组,我们首先必须检查这两种方法如何工作。
The map()
method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach()
, even if it returns undefined
, it will mutate the original array with the callback
.
map()
方法返回一个全新的数组,其中包含转换后的元素和相同数量的数据。 对于forEach()
,即使它返回undefined
,它也会使用callback
改变原始数组。
Therefore, we see clearly that map()
relies on immutability and forEach()
is a mutator method.
因此,我们可以清楚地看到map()
依赖于不变性,并且forEach()
是一种变异器方法。
4.性能速度 (4. Performance Speed)
Regarding performance speed, they are a little bit different. But, does it matter? Well, it depends on various things like your computer, the amount of data you're dealing with, and so on.
关于性能速度,它们有些不同。 但是,这有关系吗? 嗯,这取决于各种因素,例如您的计算机,正在处理的数据量等等。
You can check it out on your own with this example below or with jsPerf to see which is faster.
您可以使用下面的示例或jsPerf自行检查它,以查看哪种方法更快。
const myAwesomeArray = [1, 2, 3, 4, 5]
const startForEach = performance.now()
myAwesomeArray.forEach(x => (x + x) * 10000000000)
const endForEach = performance.now()
console.log(`Speed [forEach]: ${endForEach - startForEach} miliseconds`)
const startMap = performance.now()
myAwesomeArray.map(x => (x + x) * 10000000000)
const endMap = performance.now()
console.log(`Speed [map]: ${endMap - startMap} miliseconds`)
最后的想法 (Final Thoughts)
As always, the choice between map()
and forEach()
will depend on your use case. If you plan to change, alternate, or use the data, you should pick map()
, because it returns a new array with the transformed data.
与往常一样, map()
和forEach()
之间的选择将取决于您的用例。 如果您打算更改,替换或使用数据,则应该选择map()
,因为它会返回一个包含转换后数据的新数组。
But, if you won't need the returned array, don't use map()
- instead use forEach()
or even a for
loop.
但是,如果您不需要返回的数组,请不要使用map()
-而是使用forEach()
或什至for
循环。
Hopefully, this post clears up the differences between these two methods. If there are more differences, please share them in the comment section, otherwise thanks for reading it.
希望本文能解决这两种方法之间的差异。 如果还有更多差异,请在评论部分中分享它们,否则,感谢您阅读。
Read more of my articles on my blog
在我的博客上阅读更多文章
Photo by Franck V. on Unsplash
翻译自: https://www.freecodecamp.org/news/4-main-differences-between-foreach-and-map/
foreach 和 map