Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how to use Map and Reduce methods in JavaScript functional programming

黄舟
Release: 2017-03-08 14:53:33
Original
1160 people have browsed it

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

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

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

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

什么是函子?

有趣的一点是,通过在数组对象里添加映射,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
Copy after login

在我们定义我们的初始数组之后,我们为运行总计定义了一个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);
Copy after login

这里发生变化的是,我们定义了一个名为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);
Copy after login

这个代码稍微有点长,但是代码有点长并不总是坏事。这样写你应该看到它使代码更加清晰些,只是在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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!