Understanding Map in javascript instead of loop, javascriptmap
This article introduces the benefits and convenience map brings to our js programming:
1. What can Map do?
Map can implement the for loop function:
<!DOCTYPE html>
The advantage here is that we can write functions in map at will, which will greatly improve the code readability, as shown below:
function output(val, index, array) { console.log(val); console.log(index); console.log(array); } arr.map(output);
2. Map compatibility
ECMAScript 5 Standard defines the native map () method, so the browser compatibility is better. If you want to use it in versions earlier than IE 9, you need to introduce a polyfill or a library such as Underscore and Lodash.
3. Fast map and
Of course, using for is faster than map, but the difference is not very big. If the performance requirement is not extreme, this performance difference can be ignored.
Today, programmers will basically find a function called map in their learning process. Before discovering the map function, you may use the for loop to process scenarios where a specific row needs to be executed multiple times. In general, some data transformations are involved in this loop process.
Imperative
For example, your team's sales staff will give you a long list of email addresses. These email addresses are not properly verified, so that some are in upper case, some are in lower case, and some are in combination. The code for processing data 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 < emails.length; i++) { lowercaseEmails.push(emails[i].toLowerCase()); } return lowercaseEmails;} var validData = getEmailsInLowercase(mixedEmails);
This method is effective, but it makes a simple and common operation complicated. The use of the for Loop function involves 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 value.
- The program needs to calculate the length of the list first, and access the list as a number of times.
- The program needs to create a counter to record the current access location.
- You need to tell the program the direction of counting, but the order is not important here.
This is an imperative programming method. We seem to be deciding how to do it on the computer.
Confusions
To make the previous Code clearer and more clean, we use the map function. In any map function instructions, we will see words such as "array", "each", and "index. This shows that we can use map as a for loop that is not so "grand". In fact, it is also feasible. Now let's modify the previous Code:
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);
In this way, not only can the code be used, but the code is clearer than the for loop. In addition to less code, we do not need to tell the program to record the index and traverse the list.
However, this is not good enough. In this way, it is imperative programming. We still have too many commands. In fact, we have involved a lot of 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 about it: "computer, I need you to retrieve the first element in the list, convert it to lowercase, store it in another list, and return to this list ". On the contrary, we should think like this: "computer, I have a mail address list mixed with upper and lower cases, and I need a list of mail addresses all in lower case, this is a function that converts lowercase letters ".
var mixedEmails = ['JOHN@ACME.COM', 'Mary@FooBar.com', 'monty@spam.eggs']; function downcase(str) { return str.toLowerCase();} var validData = mixedEmails.map(downcase);
There is no doubt that this is easy to understand, and it is the essence of the program: tell others what you think, this person may be another programmer or you in the future. The above code says, "valid data is the mailbox list mapped by the lower-case conversion function ".
Passing ideas in advanced ways like this is the core principle of functional programming, and we are doing this. Combine a single simple, easy-to-understand part to build a complex program.
This method also has some additional advantages. The following table is sorted in different order:
- The lower-case conversion function provides the simplest interface: Single-value input and single-value output.
- There are not many changes, so the logic is easier to understand, test, and error-prone.
- The logic is single, so it is easy to reuse and can combine more complex functions with other functions.
- The amount of code will be significantly reduced when such Declarative Programming is followed.
Although it is common to input an anonymous function to the first parameter of map, we recommend that you put forward the function and name it properly. 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 analyze the code.
Browser support
ECMAScript 5 Standard defines the native map () method, so the browser compatibility is better. If you want to use it in versions earlier than IE 9, you need to introduce a polyfill or a library such as Underscore and Lodash.
Performance
In most cases, there is no obvious performance gap between the map function and the for Loop in actual encoding. The for loop is faster, but if you are not writing graphics or physical engines, there is no need to consider this gap. Of course, even so, unless you can determine whether these performance improvements are helpful to you, otherwise, optimization using this method is of little significance.
Summary
The logic is divided into single-Function Methods and applied to data structures. This programming method makes your code more accurate, robust, and easy to understand. Our philosophy is to be as generic as possible and to help code reuse. Learning this kind of thinking can not only help you improve Javascript, but also be reflected in most other programming languages, such as Ruby and Haskell.
So next time you want to use the for loop, consider it again. Remember, the data you want to process is not necessarily an ordinary array. You can process the object, retrieve its value, map it using the function, and finally sort out the result array.
The above is a brief introduction to map instead of loop, hoping to help you learn.
Articles you may be interested in:
- Processing java. util. Map and nested List in JSTL EL
- Simple implementation code of JS Map and List
- Simple Map implementation in javascript
- How to generate a map object in js
- Sample Code of the map method implemented by js
- Create a map in js using json
- Use gson to convert map to json format
- HashMap Code implemented by javascript
- Array. prototype. map () in Javascript
- Use of map () method to operate arrays in JavaScript