Understand that Map replaces loops in javascript

  • 2021-01-14 05:40:30
  • OfStack

This article describes the benefits and convenience that map brings to our js programming:
1. What does Map do
map can implement the functions of the for loop:


<!DOCTYPE html> 
<html> 
<head lang="en"> 
 <meta charset="UTF-8"> 
 <title></title> 
</head> 
<body> 
 
<script> 
 
 var arr = ['val1', 'val2', 'val3']; 
 
 for(var i = 0; i < arr.length; i++){ 
  console.log(arr[i]); 
  console.log(i); 
  console.log(arr); 
 } 
 arr.map(function(val, index, array) { 
  console.log(val); 
  console.log(index); 
  console.log(array); 
 }); 
 
  
  
 
</script> 
 
 
</body> 
</html> 

The nice thing about this is that we can write any function in ES12en, which will greatly improve the code readability, as follows:


 function output(val, index, array) { 
  console.log(val); 
  console.log(index); 
  console.log(array); 
 } 
 
 
 arr.map(output); 

2.Map compatibility
The ECMAScript 5 standard defines native map() methods, so browser compatibility is good. If you want to use IE prior to IE 9, you'll need to import an polyfill or use a library like Underscore, Lodash, etc.
3. Which is faster, map or for
Of course, for is faster than map, but the difference is not that big, and if the performance requirements are not extreme, the performance difference can be negligible.

Today, a function called map is almost always found in the programmer's learning process. Before the discovery of the ES34en function, you probably used the ES35en loop to deal with scenarios where you had to perform an action multiple times. In most cases, there will be some data transformation in the process of this cycle.

imperative

For example, the sales person on your team gives you a long list of email addresses. These email addresses are not properly checked, so that some are uppercase, some are lowercase, and some are mixed case. The code for data processing using the for loop is as follows:


var mixedEmails = ['JOHN@ACME.COM', 'Mary@FooBar.com', 'monty@spam.eggs'];
 
function getEmailsInLowercase(emails) {
 var lowercaseEmails = [];
 
 for (var i = 0; i &amp;lt; emails.length; i++) {
  lowercaseEmails.push(emails[i].toLowerCase());
 }
 
 return lowercaseEmails;
}
 
var validData = getEmailsInLowercase(mixedEmails);

This works, but it complicates what is actually a simple and common operation. Functions that use for loops involve a lot of unnecessary detail. 1 Some pain points are as follows:

You need to have your program create a temporary list to store the copied mail address values. You need to have the program calculate the length of the list and access the list once. You need to have the program create a counter to record the location of the current access. You need to tell the program which way to count, but the order doesn't matter here.

This is imperative programming. We seem to be dictating to the computer how to do this.

confused

To make the previous code cleaner, let's use the map function instead. In the documentation of any map function, we will see words such as "array", "each", "index", etc. This shows that we can, in fact, recycle map as the less "grand" for. Now let's change the code before 1:


var mixedEmails = ['JOHN@ACME.COM', 'Mary@FooBar.com', 'monty@spam.eggs'];
 
function getEmailsInLowercase(emails) {
 var lowercaseEmails = [];
 
 emails.map(function(email) {
  lowercaseEmails.push(email.toLowerCase());
 });
 
 return lowercaseEmails;
}
 
var validData = getEmailsInLowercase(mixedEmails);

Not only does this work, but the code is cleaner than using the for loop. In addition to having less code, we no longer have to tell the program to record indexes and walk through lists.

However, this is not good enough. So again, this is imperative programming. We're still directing too much. In fact, we get involved in a lot of unnecessary details that seem to lead the program every step of the way.

declarative

We need to change the way we think about data transformation. We don't have to think, "Computer, I need you to take the first element in the list, convert it to lowercase, store it in another list, and return this list." Instead, think, "Computer, I have a list of mixed case email addresses, and I need an all lowercase email address list. Here's a function that converts lowercase."


var mixedEmails = ['JOHN@ACME.COM', 'Mary@FooBar.com', 'monty@spam.eggs'];
 
function downcase(str) {
 return str.toLowerCase();
}
 
var validData = mixedEmails.map(downcase);

No doubt it's easier to write this way, and that's what programs are all about: tell someone, either another programmer or your future self, what you think. The code above is saying "the valid data is the mailbox list mapped using the lowercase conversion function".

Passing ideas in high-level ways like this is a core tenet of functional programming, and that's what we're doing. Build complex programs by combining simple parts that are one-to-one functional and easy to understand.

There are some additional benefits to this writing. The following table is in no particular order:

The lowercase conversion function provides the most simplified interface: single-valued input, single-valued output. Not much can be changed, so the logic is easier to understand, easier to test, and less error-prone. The logic is single, so it is easy to reuse and can be combined with other functions to create more complex functions. Going down this declarative programming route reduces the amount of code significantly.

Although it is common to pass an anonymous function as the first argument to map, it is recommended that the function be brought out and named appropriately. This will help you document the purpose of the function so that other developers can learn from the function name without having to analyze the code.

Browser support

The ES87en 5 standard defines native map() methods, so browser compatibility is good. If you want to use IE prior to IE 9, you'll need to introduce an polyfill or use a library like Underscore, Lodash, etc.

performance

For the most part, there is no significant performance gap between the map function and the for loop in the actual coding. The for loop is a little faster, but if you're not writing graphics or physics engines, this difference doesn't really matter, and even then, it doesn't make much sense to optimize in this way unless you can be sure that these performance improvements will help you.

conclusion

The method of breaking logic into single functions and applying it to data structures makes your code more accurate, robust, and easy to understand. Our philosophy is to be as generic as possible. Generality helps code reuse. Learning this way of thinking will help you improve not only in Javascript, but also in most other programming languages, such as Ruby and Haskell.

So, the next time you use the for loop, think again. Remember, the data you're dealing with doesn't have to be an array. You can process the object, get its value, use a function to map it, and then sort out the resulting array.

The above is a brief introduction about map instead of loop. I hope it will be helpful to your study.


Related articles: