foreach 和 map_每个开发人员都应该知道的forEach()和map()之间的差异
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: undefinedmyAwesomeArray.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
Franck V.在Unsplash上的照片
翻译自: https://www.freecodecamp.org/news/4-main-differences-between-foreach-and-map/
foreach 和 map
foreach 和 map_每个开发人员都应该知道的forEach()和map()之间的差异相关推荐
- java 开发人员工具_每个Java开发人员都应该知道的10个基本工具
java 开发人员工具 大家好,我们已经到了2019年的第二个月,我相信你们所有人都已经制定了关于2019年学习以及如何实现这些目标的目标. 我一直在撰写一系列文章,为您提供一些知识,使您可以学习和改 ...
- 每个Java开发人员都应该知道的10个基本工具
大家好,我们已经到了2019年的第二个月,我相信你们所有人都已经为2019年的学习目标以及如何实现这些目标制定了目标. 我一直在撰写一系列文章,为您提供一些知识,使您可以学习和改进以成为2019年更好 ...
- 正在搜索开发人员模式安装包_每个 Java 开发人员都应该知道的 10 个基本工具...
大家好,我们已经在 2019 年的第 9 个月,我相信你们所有人已经在 2019 年学到了什么,以及如何实现这些目标.我一直在写一系列文章,为你提供一些关于你可以学习和改进的想法,以便在 2019 年 ...
- pdb文件 PDB文件:每个开发人员都必须知道的 .NET PDB文件到底是什么?
pdb文件包含了编译后程序指向源代码的位置信息,用于调试的时候定位到源代码,主要是用来方便调试的. 在程序发布为release模式时,建议将 pdb文件删除, 同时,对外发布的时候,也把 pdb删除, ...
- 每个开发人员都应该知道的 15 个 IntelliJ IDEA 快捷方式
作为开发人员,高效地工作非常重要.这包括快捷方式,这些快捷方式对于快速工作和减少鼠标移动至关重要. 但是,初学者往往不知道哪些快捷方式可用或忘记使用它们.出于这个原因,在这篇文章中,我将为您提供 15 ...
- 系统分析与系统设计:每个开发人员都需要知道的 System Analysis System Design
您是一名软件工程师,有兴趣在您的职业生涯中取得进步并在就业市场上获得优势吗?学习系统设计可以在这两个方面为您提供帮助.通过了解创建现代系统以满足实际需求的过程,您将更好地准备在日常工作中提供弹性和可扩 ...
- 【vs调试】PDB 文件:每个开发人员都必须知道的
[vs调试]PDB文件:每个开发人员都必须知道的 GDB:The GNU Project Debugger, 将会包含代码中符号(自定义变量, 数据类型), 还有函数调用或类引用的关联性, 有了pdb ...
- 【vs调试】PDB文件:每个开发人员都必须知道的
PDB文件:每个开发人员都必须知道的 一 什么是PDB文件 大部分的开发人员应该都知道PDB文件是用来帮助软件的调试的.但是他究竟是如何工作的呢,我们可能并不熟悉.本文描述了PDB文件的存储和内容 ...
- PDB文件:每个开发人员都必须知道的
PDB Files: What Every Developer Must Know http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/0 ...
最新文章
- Intel汇编语言程序设计学习-第五章 过程-下
- python常用_Python常用小技巧
- java8的rmi_Java中的RMI
- 将 EndNote 文献信息导出成 BibTeX 格式(可根据label排序)以及出现三个问号
- java串口助手_java 串口调试助手 源码
- from表单iframe原网页嵌入
- 苹果发布会日期再曝光 2019新iPhone发布会定在这一天?
- vscode找不到config_vscode中的 jsconfig.json
- vscode任务栏图标突然不显示
- Orcad 16.6中批量修改网络名
- HTML和CSS基础学习
- html下拉加载原理,GitHub - gavinjzx/wxPull: 原生JS实现微信公众号或网页使用下拉加载和上拉刷新...
- android 傻瓜式编程,傻瓜式App开发:jimu 像搭积木一样搭建Android App
- Basic grammar of Python day2
- linux进化树分析的软件,进化树分析及相关软件使用说明
- 【最新】滤器完整性检测各国规定
- 关于C和C++的争论
- LoadLibrary failed with error 1114:动态链接库(DLL)初始化例程失败 解决方法
- HDMI协议介绍(一)--Overview
- FAT12模拟-C语言读取