Home > Web Front-end > JS Tutorial > body text

The difference between forEach() and map() in Array

青灯夜游
Release: 2020-12-23 18:07:15
forward
2804 people have browsed it

The difference between forEach() and map() in Array

Related recommendations: "javascript video tutorial"

Today we take a look at Array.forEach() in Array The difference between the Array.map() method. The

forEach() and map() methods are usually used to traverse Array elements, but there is almost no difference, let’s introduce them one by one.

1. Return value

forEach() method returns undefined, while map()Return a new array containing the converted elements.

const numbers = [1, 2, 3, 4, 5];

// 使用 forEach()
const squareUsingForEach = [];
numbers.forEach(x => squareUsingForEach.push(x*x));

// 使用 map()
const squareUsingMap = numbers.map(x => x*x);

console.log(squareUsingForEach); // [1, 4, 9, 16, 25]
console.log(squareUsingMap);     // [1, 4, 9, 16, 25]
Copy after login

Since forEach() returns undefined, we need to pass an empty array to create a new converted array. The map() method does not have such a problem, it directly returns the new converted array. In this case, it is recommended to use the map() method.

2. Link other methods

map()method output can be linked to other methods (such as reduce(), sort(), filter()) are chained together to perform multiple operations in one statement.

On the other hand, forEach() is a terminal method, which means it cannot be chained with other methods because it returns undefined.

We use the following two methods to find the sum of squares of each element in the array:

onst numbers = [1, 2, 3, 4, 5];

// 使用 forEach()
const squareUsingForEach = []
let sumOfSquareUsingForEach = 0;
numbers.forEach(x => squareUsingForEach.push(x*x));
squareUsingForEach.forEach(square => sumOfSquareUsingForEach += square);

// 使用 map()
const sumOfSquareUsingMap = numbers.map(x => x*x).reduce((total, value) => total + value)
;

console.log(sumOfSquareUsingForEach); // 55
console.log(sumOfSquareUsingMap);     // 55
Copy after login

When multiple operations are required, use forEach()The method is one A very tedious job. We can use the map() method in this case.

3. Performance

// Array:
var numbers = [];
for ( var i = 0; i < 1000000; i++ ) {
    numbers.push(Math.floor((Math.random() * 1000) + 1));
}

// 1. forEach()
console.time("forEach");
const squareUsingForEach = [];
numbers.forEach(x => squareUsingForEach.push(x*x));
console.timeEnd("forEach");

// 2. map()
console.time("map");
const squareUsingMap = numbers.map(x => x*x);
console.timeEnd("map");
Copy after login

This is after running the above code on Google Chrome v83.0.4103.106 (64-bit) on MacBook Pro the result of. It is recommended to copy the above code and try it in your own console.

forEach: 26.596923828125ms
map:     21.97998046875ms
Copy after login

Obviously, the map() method is better than forEach()converting elements.

4. Interrupt traversal

Neither of these two methods can be interrupted by break, otherwise an exception will be thrown:

const numbers = [1, 2, 3, 4, 5];

// break; inside forEach()
const squareUsingForEach = [];
numbers.forEach(x => { 
  if(x == 3) break; // <- SyntaxError 
  squareUsingForEach.push(x*x);
});

// break; inside map()
const squareUsingMap = numbers.map(x => {
  if(x == 3) break; // <- SyntaxError 
  return x*x;
});
Copy after login

The above code will throw SyntaxError:

ⓧ Uncaught SyntaxError: Illegal break statement
Copy after login

If you need to interrupt the traversal, you should use a simple for loop or for-of/for-incycle.

const numbers = [1, 2, 3, 4, 5];

// break; inside for-of loop
const squareUsingForEach = [];
for(x of numbers){
  if(x == 3) break;
  squareUsingForEach.push(x*x);
};

console.log(squareUsingForEach); // [1, 4]
Copy after login

5. Finally

It is recommended to use map() to convert the elements of the array because it has short syntax, chainability and better performance.

If you do not want to return the array or do not convert the elements of the array, use the forEach() method.

Finally, if you want to stop or break the convenience of an array based on some condition, you should use a simple for loop or a for-of / for-in loop.

Original address: https://codingnconcepts.com/javascript/difference-between-foreach-and-map-in-javascript-array/

Author: Ashish Lahoti

Translation address: https://segmentfault.com/a/1190000038421334

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of The difference between forEach() and map() in Array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!