Understanding the techniques of map substitution loop _javascript in JavaScript

Source: Internet
Author: User
Tags data structures lowercase mixed

This article introduces the benefits and conveniences that map brings to our JS programming:
What can 1.Map do?
The map can implement the For loop functionality:

<! DOCTYPE html> 
 
 

The advantage here is that we are free to write functions in the map so that the code is much more readable, 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 the native map () method, so the browser is better compatible. If you want to use it before IE 9, you need to introduce a polyfill or use a library like underscore, lodash, and so on.
3.map and for which fast
Of course, using for is faster than map, but the difference is not great, and if the performance requirements are not extreme, this performance difference can be ignored.

Today, a function called map is basically found in the programmer's learning process. Before discovering the map function, you might use a for loop to handle a scenario where you need to perform a behavior multiple times. In general, some data transformations will be associated with this cycle.

Command-

For example, the sales staff of your team give you a long email address list. These email addresses are not well calibrated, and some are capitalized, some are lowercase, and some are mixed in case. The code for data processing using a 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 &lt; emails.length i++) {
  Lowercaseemails.push (emails[i].tolowercase ());
 }
 
 return lowercaseemails;
}
 
var validdata = getemailsinlowercase (mixedemails);

This is effective, but it complicates an operation that is actually simple and common. Functions that use a for loop involve a lot of unnecessary detail. Some of the pain points are as follows:

    • You need to have the program create a temporary list to store the copied mail address values.
    • You need to have the program calculate the length of the list to access the list as a number of times.
    • You need to have the program create a counter to record the current access location.
    • You need to tell the program the direction of the count, but the order is not important here.

This is an imperative programming method. We seem to dictate to the computer how to do this thing.

Confused

To make the previous code clearer and cleaner, we use the map function instead. In any description document of the map function, we will see words such as "array", "each", "index", and so on. This suggests that we can use the map as a less "grand" for loop, which is actually possible. Now to 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);

This writing is not only available, but the code is clearer than using a for loop. In addition to the amount of code, we don't have to tell the program to log the direction of indexing and traversing the list.

However, this is not good enough. This is a command-and-write program. We still command too much. In fact, we are involved in a lot of unnecessary details, seems to be in the hands of the program to take each step.

Declaration type

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 in the list, then convert it to lowercase, store it in another list, and then return to the list." Instead, we should think: "Computer, I have a mixed case list of mailing addresses, and I need a list of all lowercase mailing addresses, which is a function that can be converted to lowercase."

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 easier to understand, and that is the nature of the program: Tell others what you think, this person may be another programmer or you in the future. The code above says that "valid data is a list of mailboxes that are mapped using lowercase conversion functions."

Passing ideas in a high-level way like this is the core principle of functional programming, and that's what we're doing. A complex program is built by combining a single feature, easily understandable, simple parts.

There are some additional benefits to this writing. The following table is sorted in a separate order:

    • The lowercase conversion function provides the simplest interface: Single value input, single value output.
    • There are not many places to change, so logic is easier to understand, easier to test, and less prone to error.
    • Logic is simple, so it is easy to reuse and can combine more complex functions with other functions.
    • Along this declarative programming route, the amount of code is significantly reduced.

Although it is common to pass the first parameter of a map to an anonymous function, it is recommended that the function be presented and properly named. This will help you write down the intent of writing this function so that other developers can understand the function through the function name without having to bother analyzing the code.

Browser support situation

The ECMAScript 5 standard defines the native map () method, so the browser is better compatible. If you want to use it before IE 9, you need to introduce a polyfill or use a library like underscore, lodash, and so on.

Performance features

In most cases, there is no significant performance gap between the map function and the for loop in the actual encoding. The For loop is a little faster, but if you're not writing graphics or physics engines, this gap doesn't have to be considered, but even so, unless you can be sure that these performance improvements are helpful, it's not very meaningful to optimize this way.

Summarize

By dividing logic into a single functional approach and applied to data structures, this programming approach makes your code more accurate, robust, and easy to understand. Our philosophy is to be as generic as possible, and universal can help code reuse. Learning this way of thinking not only helps you improve your Javascript level, it can also be embodied in most other programming languages, such as Ruby and Haskell.

So the next time you want to use the For loop, reconsider. Remember, the data you're dealing with is not necessarily an ordinary array, you can handle the object, take out its value, use the function to map it, and then sort out the result array.

The above is a simple introduction to the map instead of the cycle, I hope to help you learn.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.