This article introduces the benefits and conveniences that map brings to our js programming:
What can I do
Map can implement the function of a 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 < ; i++){ (arr[i]); (i); (arr); } (function(val, index, array) { (val); (index); (array); }); </script> </body> </html>
The advantage here is that we can write functions in the map at will, so that the readability of the code will be greatly improved, as follows:
function output(val, index, array) { (val); (index); (array); } (output);
Compatibility
The ECMAScript 5 standard defines the native map() method, so the browser compatibility is better. If you want to use it in versions before IE 9, you need to introduce a polyfill or use Underscore, Lodash and other libraries.
Which one is faster or for
Of course, using for will be faster than map, but the difference is not very big. If the performance requirements are not to the extreme, this performance difference can be ignored.
Nowadays, in the process of programmers learning, they will basically find a function called map. Before you discover a map function, you may use a for loop to handle scenarios that require a certain behavior to be executed multiple times. Generally speaking, this cycle will be accompanied by some data transformation.
Command
For example, your team’s salesperson gives you a long list of email addresses. These email addresses were not well verified when obtaining them, so that some were capitalized, some were lowercase, and some were mixed with uppercase. The code for data processing using a for loop is as follows:
var mixedEmails = ['JOHN@', 'Mary@', 'monty@']; function getEmailsInLowercase(emails) { var lowercaseEmails = []; for (var i = 0; i &lt; ; i++) { (emails[i].toLowerCase()); } return lowercaseEmails; } var validData = getEmailsInLowercase(mixedEmails);
This approach is effective, but it complicates an actually simple and common operation. Functions using for loops involve a lot of unnecessary details. Some pain points are as follows:
- You need to have the program create a temporary list to store the copied mail address values.
- The program needs to first calculate the length of the list and access the list with this number of times.
- You need to have the program create a counter to record the current access location.
-
The program needs to be told the direction of the count, but the order does not matter here.
This is an imperative programming method. We seem to be dictating how to do this to the computer.
Puzzled
In order to make the previous code clearer and more tidy, we used the map function instead. In the description document of any map function, we will see words such as "array", "each", "index". This shows that it is actually feasible to use maps as a less "sovereign" for loop. Now let’s modify the previous code:
var mixedEmails = ['JOHN@', 'Mary@', 'monty@']; function getEmailsInLowercase(emails) { var lowercaseEmails = []; (function(email) { (()); }); return lowercaseEmails; } var validData = getEmailsInLowercase(mixedEmails);
This way, not only can it be used to write, but the code is clearer than using a for loop. In addition to the smaller amount of code, we no longer have to tell the program to record the index and traverse the list.
However, this is not good enough. This is still imperative programming. We still command too much. In fact, we are involved in many unnecessary details, and it seems that we are taking every step of the program.
Declarative
We need to change the way we think about data transformation. We don't need to think: "Computer, I need you to take out the first element of the list, convert it to lowercase, store it in another list, and finally return to this list." Instead, we should think like this: "Computer, I have a mixed case list of email addresses, and I need a list of email addresses that are all lowercase, which is a function that can perform lowercase conversion".
var mixedEmails = ['JOHN@', 'Mary@', 'monty@']; function downcase(str) { return (); } var validData = (downcase);
There is no doubt that this writing is easier to understand, and this is the essence of the program: tell others your ideas, which may be another programmer or future you. The above code says "Valid data is a mailbox list mapped using lowercase conversion functions".
Passing ideas with advanced ways like this is the core principle of functional programming, and we are doing that. Combine simple parts of a single function, easy to understand to build complex programs.
There are some additional benefits to this writing. The following tables are sorted in no order:
- Lowercase conversion functions provide the simplified interface: single-value input, single-value output.
- There are not many places that can be changed, so the logic is easier to understand, easy to test, and less prone to errors.
- The logic is single, so it is easy to reuse and can be combined with other functions to create more complex functions.
-
If you follow this declarative programming route, the amount of code will be significantly reduced.
Although it is common to pass anonymous functions to the first parameter of map, it is recommended to propose the function and name it reasonably. This can help you record the intention of writing this function, so that other developers can understand the function through the function name without having to work hard to analyze the code.
Browser support
The ECMAScript 5 standard defines the native map() method, so the browser compatibility is better. If you want to use it in versions before IE 9, you need to introduce a polyfill or use Underscore, Lodash and other libraries.
Performance
In most cases, there is no significant performance gap between the map function and the for loop in actual encoding. The for loop is slightly faster, but if you are not writing graphics or physics engines, there is no need to consider this gap. Of course, even so, unless you can determine that these performance improvements are helpful to you, it is not very meaningful to optimize this way.
Summarize
A method of dividing logic into a single function and applying it to data structures will make your code more accurate, robust and easy to understand. Our philosophy is to be as general as possible, and universal can help reuse the code. Learning this way of thinking can not only help you improve your Javascript level, but it can also be reflected in most other programming languages, such as Ruby and Haskell.
So, the next time you want to use a for loop, rethink it. Remember, the data you want to process is not necessarily an ordinary array. You can process the object, take out its value, then use the function to map, and finally sort out the result array.
The above is a brief introduction about map instead of loops. I hope it will be helpful to everyone's learning.