Array.map() and Array.forEach() in JavaScript

Preface

There are two most common ways to traverse an array in JavaScript

  • useArray.map()
  • useArray.forEach()

Both methods allow you to iterate over an array and perform operations on the array elements. But there are some key differences between these methods that you need to remember. Therefore, you need to decide which of the two methods to use based on the situation.

In this article, I will explain both methods and the use cases where you can use them.

Array.map()

map()Method allows you to create a new array filled with the results of calling the provided callback function on each element in the calling array.

Below is map()the definition of the method.

map(function(element, index, array) { /* ... */ 
}, thisArg) 

map()The callback function in will always be called with three arguments.

  • element value
  • index of element
  • Array object being traversed

If we want to provide a value to a method explicitly this, we can thisArgdo so using parameters.

So, let's say we have an numbersarray called , we can iterate over that array using the method like this map().

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

// 接收数组的每一个参数
// 将他们乘以2
// 返回一个新的数组是他们的结果
const mapNumbers = numbers.map(function(number) {return number * 2;
});

console.log(mapNumbers);
// [2, 4, 6, 8] 

map()The method will iterate over numbersthe array, calling the provided callback function on each array element, and return a brand new array.

One thing to note here is that map()the original array is not changed. Therefore, the array of numbers remains unchanged.

When to useArray.map()

In the case where you want to use the array returned by the method, you should use map()the method.

Take the following React component as an example.

export default function App() {const posts = [{ id: 1, title: "Hello World",},{ id: 2,title: "Hello China", }];const sidebar = posts.map((post) => (<li key={post.id}>{post.title}</li>));console.log(sidebar);return (<div><ul> {sidebar}</u></div>);
} 

In this example, we have an postsarray of objects named that we want to render. So, in this case, we can use map()the method since we want to assign the returned array to sidebara variable.

React then iterates through this array and uses props.childrento render the desired output.

In this case, map()this should be your "go-to" method.

When not to useArray.map()

When not to use Array.map(). The answer is simple. This method should not be used if you are not using the array it returns. You should avoid using it entirely map().

Array.forEach()method

forEach()Method allows you to iterate over the array and execute the provided function once for each array element, map()exactly like the method. But there are some differences.

  • It does not return a new array.
  • It will always return undefined.

Below is forEach()the definition of the method.

forEach(function(element, index, array) { /* ... */ 
}, thisArg) 

forEach()The callback function in will always be called with three arguments.

  • element value
  • index of element
  • Array object being traversed

If we want to provide a value to a method explicitly this, we can thisArgdo so using parameters.

Below is a forEach()simple example demonstrating the usage of the method.

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

// 接收数组的每一个参数
// 将他们乘以2
// 并将他们打印出来
numbers.forEach(function(number) {mapNumbers.push(number * 2);
});

console.log(mapNumbers);
// [ 2, 4, 6, 8 ] 

Since forEach()the method does not return a new array, we need to manually push the array elements to the newly created array in the callback function.

Also note that we are effectively mutating mapNumbersthe array here, unlike map()the method, which is not always a good practice.

When to useArray.forEach()

When you just want to perform some operation on the array elements, you can always use forEach()the method. For example, in the case where you just want to print the array elements.

Another use case is to use it at the end of the chain when you want to perform some side effects such as logging.

When not to useArray.forEach()

You should easily avoid using the method when you need to return a newly constructed array forEach(), as that method will always return undefineda value.

So, when you want to render array elements in a React component, you cannot use forEach.

at last

We have compiled 75 JS high-frequency interview questions, and provided answers and analysis. This can basically guarantee that you can cope with the interviewer's questions about JS.



Friends in need can click on the card below to receive it and share it for free

Guess you like

Origin blog.csdn.net/web2022050901/article/details/129771488