search
HomeWeb Front-endJS TutorialDetailed explanation of how to use Map and Reduce methods in JavaScript functional programming

With all the talk about workflows supporting the amazing new features coming to ECMAScript 6, it’s easy to forget that ECMAScript 5 brought us some great tools and methods to support functional programming in JavaScript that we now have Ready to use. The main ones among these function methods are the map() method and reduce() method based on JavaScript array objects.

If you haven’t used the map() and reduce() methods yet, now is the time to start using them. Most of today's JavaScript development platforms natively support ECMAScript5. Using the Map method and the reduce method can make your code more concise, easier to read and easier to maintain, and take you on the road to simpler functional development.

Performance: A Warning

Of course, when the reality is to maintain improved performance, the readability and maintainability of your code have to be balanced between the two. Today's browsers use more cumbersome traditional techniques such as for loops to perform more efficiently.

The way I write code is usually to put readability and maintainability first in writing code, and then if I find that there is a problem with the code running in real situations, I will go to improve performance. to optimize the code. It is difficult to optimize code prematurely, and this optimization will make it difficult to write code later.

It is worth considering that using methods such as map() and reduce() in the JavaScript engine can better improve the performance of the code, rather than expecting that the browser will make optimizations to improve performance in the future. Unless I hit a performance wall, I prefer to have fun writing code, yet I'm always ready to make adjustments to keep my code performant in case I need them, even if doing so makes my code less attractive. force.

Using the Map method

Mapping is a basic functional programming technique that works on all elements in an array and creates other arrays of the same length and with transformed content.

In order to make what I just said more concrete, I came up with a simple usage example. For example, imagine you have an array that contains character data, and you need to convert them into another array that contains the length of each character data. (I know, that's not rocket science complicated, it's something you'll often have to do when writing complex applications, but understanding how it works in a simple example like this one will help you use it, In this case, you can add real data values ​​to it in your code).

You may know how to use a for loop on an array as I just described. It might look something like this:

var animals = ["cat","dog","fish"];
var lengths = [];
var item;
var count;
var loops = animals.length;
for (count = 0; count < loops; count++){
  item = animals[count];
  lengths.push(item.length);
}
console.log(lengths); //[3, 3, 4]

All we need to do is define a handful of variables: an array named animals that contains the character data we need, and an empty array named lengths for future use. Contains the length of the data output of our operation array, and a variable called item. This variable is used to temporarily store the array items we need to operate each time the loop traverses the array. We define a for loop, which has an internal variable and a loop variable to initialize our for loop. We then loop through each item until the length of the iterated array is equal to the length of the animals array. Each time through the loop we calculate the character length of the iteration item and save it to the lengths array.

Note: What needs to be discussed is that we can write the above code more concisely, without the item variable, and directly put the length of animals[count] into the lengths array, so there is no need for an intermediate conversion process. Doing this can save us a little bit of code space, but it also makes our code a little hard to read, even for this very simple example. Likewise, to make the code more efficient and less straightforward, we might use the known length of the animals array to initialize our lengths array via new Array(animals.length) and then index it instead of using push Method to insert option data length. It depends on how you plan to use the code in reality.

There are no technical errors in this implementation. It works with any standard JavaScript engine, and it gets the job done. Once you know how to use the map() method, implementing it this way can seem clumsy.

Let me show you how the above code is implemented using the map() method:

var animals = ["cat","dog","fish"];
var lengths = animals.map(function(animal) {
  return animal.length;
});
console.log(lengths); //[3, 3, 4]

In this small example, we first create an array again for our animal type animals variable. However, the only other variable we need to declare is the lengths variable, and we assign its value directly to the result of mapping an anonymous inline function to each element of the animals array.

The anonymous function performs the operation on each animal, and then returns the character length of the animal. The result of this is that lengths becomes an array with the same length as the original animals array, and this array contains the length of each character.

这种方式需要注意的一些事情。首先,它比最初编写的代码更简洁。其次,我们仅需要申明更少的变量。更少的变量意味着在全局命名空间里杂音更少,并且如果相同代码的其他部分使用了相同的变量名就会减少碰撞的机会。最后,我们的变量不可能从头到脚都会改变它们的值。随着你深入函数式编程,你将会欣赏使用常量和不变的变量的优雅的能力,现在开始使用并不算早。

这种实现方式的另一个优点是,我们可以通过在整个代码编写过程中通过将代码放进一个个命名的函数里而简化代码而有机会提升自己编写代码的多功能性。匿名的内联函数看着有些乱,并且使得重复使用代码更困难。我们可以定义一个命名为getLength()的函数,并且像下面的方式来使用:

var animals = ["cat","dog","fish"];
function getLength(word) {
  return word.length;
}
console.log(animals.map(getLength)); //[3, 3, 4]

看看上面的代码看上去多简洁啊?只是把你处理数据的部分映射一下就使你的代码达到一个全新的功能水平。

什么是函子?

有趣的一点是,通过在数组对象里添加映射,ECMAScript5把基本的数组类型变成了一个完整的函子,这使得函数式编程对我们来说更加的容易。

根据传统的函数编程定义,一个函子需要满足三个条件:

  • 1.它保存着一组值。

  • 2.它实现了一个map函数来操作每一个元素。

  • 3.它的map函数返回一个具有同样大小的函子。

这个将会在你下一次的JavaScript聚会上被翻来覆去的讨论。

如果你想了解更多关于函子的信息,你可以看看Mattias Petter Johansson录制的关于这方面的视频。

使用Reduce方法

Reduce()方法在ECMAScript5里也是新增的,而且它和map()方法很类似,除了不产生其他的函子,reduce()方法产生的一个结果是它可能是任何类型。例如,设想一下,如果你想得到我们animals数组里的所有字符长度都分别作为一个数字然后相加的结果。你也许会像下面这样做:

var animals = ["cat","dog","fish"];
var total = 0;
var item;
for (var count = 0, loops = animals.length; count < loops; count++){
  item = animals[count];
  total += item.length;
}
console.log(total); //10

在我们定义我们的初始数组之后,我们为运行总计定义了一个total变量,并把它的初始值设为0。我们也定义一个变量item来保存每一次for循环迭代animals数组的迭代值,并且再定义一个count变量作为一个循环计数器,并且用这两个变量来初始化我们的迭代。然后我们运行for循环来迭代animals数组里的所有字符数据,每次迭代都会把迭代的结果保存到item变量。最终我们把每一次迭代到的item的长度加到我们的total变量里就可以了。

这种实现方式也没有任何的技术错误。我们从定义一个数组开始,然后得到一个结果值就结束了。但是如果我们使用了reduce()方法,我们可以使上面的代码更加简单明了:

var animals = ["cat","dog","fish"];
var total = animals.reduce(function(sum, word) {
  return sum + word.length;
}, 0);
console.log(total);

这里发生变化的是,我们定义了一个名为total的新变量,并且把执行animals数组对象的reduce方法的返回值分配给它,在reduce方法里有两个参数:一个匿名内联function方法,和初始化total的值为0。对于数组中的每一个项reduce()方法都会执行,它在数组的那一项上执行这个function函数,并且把它添加到运行总计,然后再进行下一次迭代。这里我们的内联function方法有两个参数:运行总计,和当前程序正在处理的从数组中获取的字符。这个function函数把当前total的值添加到当前word的长度上。

注意的是:我们设置reduce()方法的第二个参数值为0,这样做确定了total变量包含的是一个数值。如果没有第二个参数reduce方法仍然可以执行,但是执行的结果将不是你期望的那样。(你可以试试并且可以看看当运行总计结束后你是否能推测出JavaScript所使用的编程逻辑。)

那看上去似乎比它需要做的更有一点复杂,因为当调用reduce()方法时需要在一个内联function里综合的定义。我们再那么做一次,但是首先让我们定义一个命名的function函数,而不再使用匿名内联函数:

var animals = ["cat","dog","fish"];
var addLength = function(sum, word) {
  return sum + word.length;
};
var total = animals.reduce(addLength, 0);
console.log(total);

这个代码稍微有点长,但是代码有点长并不总是坏事。这样写你应该看到它使代码更加清晰些,只是在reduce()方法里发生了一点变化。

该程序里reduce()方法有两个参数:一个function函数,用来调用数组里的每一个元素,和一个为total变量设置的运行总计初始值。在这个代码示例中,我们放入了一个名为addLength的新function和为运行总计变量赋初始值为0。在上一行代码中,我们定义了一个名为addLength的function函数,这个函数也需要两个参数:一个当前和一个要处理的字符串。

Conclusion

Frequent use of the map() method and the reduce() method will provide options for your code to be more concise, more versatile, and more maintainable. They also pave the way for you to use more functional JavaScript techniques.

The map() method and the reduce() method are just two of the new methods added to ECMAScript5. You'll know from using them today that the improvements in code quality and developer satisfaction outweigh any temporary impact on performance. Before judging whether the map() method and reduce() method are suitable for your application, try to use functional function technology to develop and measure its impact in your real world, and then judge whether to use it.


#

The above is the detailed content of Detailed explanation of how to use Map and Reduce methods in JavaScript functional programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft