In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian for you to introduce in detail "what is the difference between map () and forEach () in JavaScript", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "what is the difference between map () and forEach () in JavaScript" can help you solve your doubts.
What are map () and forEach ()?
Map and forEach are helper methods in an array that can easily loop through an array. We used to loop through an array like this without any helper functions.
Var array = ['1','2','3']; for (var I = 0; I
< array.length; i += 1) { console.log(Number(array[i])); } // 1 // 2 // 3 自JavaScript时代开始以来,就一直存在 for 循环。它包含3个表达式:初始值,条件和最终表达式。 这是循环数组的经典方法。从ECMAScript 5开始,新功能似乎使我们更加快乐。 map map 的作用与 for 循环完全相同,只是 map 会创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。 它需要两个参数:一个是稍后在调用 map 或 forEach 时调用的回调函数,另一个是回调函数被调用时使用的名为 thisArg 的上下文变量。 const arr = ['1', '2', '3']; // 回调函数接受3个参数 // 数组的当前值作为第一个参数 // 当前值在数组中的位置作为第二个参数 // 原始源数组作为第三个参数 const cb = (str, i, origin) =>{console.log (`${I}: ${Number (str)} / ${origin}`);}; arr.map (cb); / / 0: 1 / 1 Magi 2 / / 1: 2 / 1 Magi 3 / / 2: 3 / 1
The callback function can be used as follows.
Arr.map ((str) = > {console.log (Number (str));})
The result of map is not equal to the original array.
Const arr = [1]; const new_arr = arr.map (d = > d); arr = = new_arr; / / false
You can also pass objects to map as thisArg.
Const obj = {name: 'Jane'}; [1] .map (function () {/ / {name:' Jane'} console.dir (this);}, obj); [1] .map (() = > {/ / window console.dir (this);}, obj)
The object obj becomes the thisArg of map. However, the arrow callback function cannot have obj as its thisArg.
This is because the arrow function is different from the normal function.
ForEach
ForEach is another loop function of an array, but map and forEach are different in use. Map and forEach can take two parameters-- the callback function and thisArg, which are used as their this.
Const arr = ['1arguments,' 2arguments,'3']; / / the callback function accepts the current value of the three parameters / / the current value of the array as the first parameter / / the position of the current value in the array as the second parameter / / the original source array as the third parameter const cb = (str, I, origin) = > {console.log (`${I}: ${Number (str)} / ${origin}`);} Arr.forEach (cb); / / 0: 1 / 1Jing 2Jing 3 / / 1: 2 / 1Med 2jue 3 / / 2: 3 / 1Met 2Jing 3
What's the difference?
Map returns a new array of its original array, but forEach does not. But they all ensure the immutability of the original object.
(d = > d + 1). Map (d = > d + 1); / / [2pr 3,4]; [1Met 2Jet 3] .forEach (d = > d + 1); / / undefined
If you change the values within an array, forEach cannot guarantee the immutability of the array. This method is guaranteed to remain unchanged only if you do not touch any of the values in it.
[{a: 1, b: 2}, {a: 10, b: 20}] .forEach ((obj) = > obj.a + = 1); / / [{a: 2, b: 2}, {a: 11, b: 21}] / array changed!
When to use map () and forEach ()?
Since the main difference between them is whether there is a return value, you will want to use map to make a new array, while forEach is only used to map to the array.
This is a simple example.
Const people = [{name: 'Josh', whatCanDo:' painting'}, {name: 'Lay', whatCanDo:' security'}, {name: 'Ralph', whatCanDo:' cleaning'}]; function makeWorkers (people) {return people.map ((person) = > {const {name, whatCanDo} = person; return My name is {name}, I can do {whatCanDo}});} makeWorkers (people)
For example, in React, map is a very common way to make elements, because map creates and returns a new array after manipulating the data of the original array.
Const mySubjectId = ['154,' 773, '245]; function countSubjects (subjects) {let cnt = 0; subjects.forEach (subject = > {if (mySubjectId.includes (subject.id)) {cnt + = 1;}}); return cnt;} countSubjects ([{id:' 223, teacher: 'Mark'}, {id:' 154, teacher: 'Linda'}]); / 1
On the other hand, forEach is useful when you want to do something with the data without creating a new array. By the way, you can use the filter refactoring example.
Subjects.filter (subject = > mySubjectId.includes (subject.id)) .length
To sum up, I suggest you use map when creating a new array, and use forEach when you don't need to make a new array, but when you want to do something with the data.
Speed comparison
Some posts mentioned that map is faster than forEach. So, I wonder if it's true. I found this comparison.
The code looks very similar, but the result is the opposite. Some tests say forEach is faster, others say map is faster. Maybe you're telling yourself that map/forEach is faster than the others, and you're probably right. To be honest, I'm not sure. I think in modern Web development, readability is much more important than the speed between map and forEach.
But one thing is certain-- both are slower than JavaScript's built-in for loop.
After reading this, the article "what is the difference between map () and forEach () in JavaScript" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it to understand it. If you want to know more about related articles, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.