Home Web Front-end JS Tutorial Understand Map instead of loop in javascript_javascript skills

Understand Map instead of loop in javascript_javascript skills

May 16, 2016 pm 03:13 PM
javascript map

本文介绍了map给我们的js编程带来的好处及便利:
1.Map能干什么
map可以实现for循环的功能:

<!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> 
Copy after login

这里的好处是,我们可以随意在map里面写函数,这样的话代码可读性会大大提高,如下:

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

2.Map的兼容性
ECMAScript 5 标准定义了原生的 map() 方法,所以浏览器兼容性较好。如果你想在 IE 9 之前的版本中使用,就需要引入一个 polyfill 或使用 Underscore、Lodash 之类的库了。
3.map和for哪个快
当然,使用for会比map快点,但是差别不是很大,如果对性能要求没有到极致的地步,这点性能差别可以忽略。

如今,在程序员学习过程中基本都会发现一个叫 map 的函数。在发现 map 函数之前,你可能都会使用 for 循环来处理需要多次执行某一行为的场景。一般情况下,在这个循环过程中都会伴随一些数据变换。

命令式

例如,你团队的销售人员交给你一个很长的电邮地址列表。这些邮箱地址获取的时候并没有经过很好地校验,以至于有些是大写的,有些是小写的,还有一些是大小写混合的。使用 for 循环进行数据处理的代码如下:

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);
Copy after login

这样的做法是有效的,但却把一个实际上简单常见的操作变得复杂。使用 for 循环的函数牵扯了很多不必要的细节。一些痛点如下:

  • 需要让程序创建一个临时列表来存储复制的邮件地址值。
  • 需要让程序先计算列表的长度,以此为次数访问一遍列表。
  • 需要让程序创建一个计数器用来记录当前访问的位置。
  • 需要告诉程序计数的方向,但顺序在这里并不重要。

这是命令式的编程方法。我们似乎在口述给电脑该怎么做这件事。

困惑

为了使之前的代码更加清晰整洁,我们改用 map 函数。在任何 map 函数的说明文档中,我们都会看到诸如 “array”、“each”、“index”之类的词。这表明,我们可以把 map 当做不那么“隆重”的 for 循环使用,事实上也是可行的。现在来修改一下之前的代码:

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);
Copy after login

这样写不仅能用,而且代码比使用 for 循环更加清楚。除了代码量更少,我们也不用再告诉程序去记录索引和遍历列表的方向了。

然而,这还不够好。这样写还是命令式的编程。我们还是指挥的太多。实际上我们牵涉了很多不必要的细节,似乎都在领着程序的手走每一步。

声明式

我们需要改变我们关于数据变换的思考方式。我们不需要想着:“电脑啊,我需要你取出列表中第一个元素,然后把它转换成小写,再存储到另一个列表中,最后返回这个列表”。相反,我们应该这样想:“电脑,我这有一个混合了大小写的邮件地址列表,而我需要一个全是小写的邮件地址列表,这是一个能够进行小写转换的函数”。

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

There is no doubt that this way of writing is easier to understand, and this is the essence of programming: telling other people your ideas, this person may be other programmers or you in the future. The above code is saying "valid data is the mailbox list mapped using the lowercase conversion function".

Using advanced ways like this to communicate ideas is a core principle of functional programming, and we do just that. Build complex programs by combining simple parts with a single function that are easy to understand.

This way of writing has some additional benefits. The following table is in no particular order:

  • The lowercase conversion function provides the simplest interface: single value input, single value output.
  • There are not many places that can be changed, so the logic is easier to understand, easier to test, and less prone to errors.
  • The logic is simple, 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 an anonymous function into the first parameter of map, it is recommended to extract the function and name it appropriately. 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

The ECMAScript 5 standard defines the native map() method, so browser compatibility is better. If you want to use it in versions before IE 9, you need to introduce a polyfill or use a library such as Underscore or Lodash.

Performance

In most cases, there is no obvious performance gap between map functions and for loops in actual coding. The for loop is slightly faster, but if you are not writing a graphics or physics engine, there is no need to consider this difference. Of course, even so, unless you are sure that these performance improvements will help you, it makes sense to optimize in this way. Not big.

Summary

Breaking logic into single-function methods and applying them to data structures will make your code more accurate, robust, and easy to understand. Our philosophy is to be as general as possible, which helps code reuse. Learning this way of thinking will not only help you improve your Javascript skills, but it can also be reflected in most other programming languages, such as Ruby and Haskell.

So, next time you’re about to use a for loop, think again. Remember, the data you want to process is not necessarily an ordinary array. You can process the object, take out its value, use a function to map it, and finally sort out the result array.

The above is a brief introduction about map instead of loop. I hope it will be helpful to everyone's learning.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Optimize the performance of Go language map Optimize the performance of Go language map Mar 23, 2024 pm 12:06 PM

Optimizing the performance of Go language map In Go language, map is a very commonly used data structure, used to store a collection of key-value pairs. However, map performance may suffer when processing large amounts of data. In order to improve the performance of map, we can take some optimization measures to reduce the time complexity of map operations, thereby improving the execution efficiency of the program. 1. Pre-allocate map capacity. When creating a map, we can reduce the number of map expansions and improve program performance by pre-allocating capacity. Generally, we

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles