如何在JavaScript中使用map(),filter()和reduce()

介绍 (Introduction)

Functional programming in JavaScript benefits code readability, maintainability, and testability.

JavaScript中的函数式编程可提高代码的可读性,可维护性和可测试性。

One of tools from the functional programming mindset is programming in an array-processing style. This entails taking arrays as your fundamental data structure. Then, your program becomes a series of operations on elements in the array.

功能编程思维方式中的一种工具是以数组处理方式进行编程。 这需要将数组作为基本数据结构。 然后,您的程序将对数组中的元素进行一系列操作。

There are many contexts in which this is useful, such as mapping AJAX results to React components with map, removing extraneous data with filter, and using reduce. These functions, called “Array Extras”, are abstractions over for loops. There is nothing you can do with with these functions that you can’t achieve with for, and vice-versa.

在许多情况下这很有用,例如使用map将AJAX结果映射到React组件,使用filter删除无关的数据以及使用reduce 。 这些函数称为“ Array Extras”,是for循环的抽象。 这些功能对for是无能为力的,反之亦然。

In this tutorial, we’ll develop a deeper understanding of functional programming in JavaScript by taking a look at filter, map, and reduce.

在本教程中,我们将通过查看filtermapreduce加深对JavaScript函数编程的了解。

for迭代 (Iteration with for)

We use for loops to iterate over every item in an array. Usually, we do something to each item along the way.

我们使用for循环来遍历数组中的每个项目。 通常,我们会在此过程中对每个项目进行处理。

One example would be capitalizing every string in an array.

一个示例是将数组中的每个字符串都大写。

const strings = ['arielle', 'are', 'you', 'there'];
const capitalizedStrings = [];

for (let i = 0; i < strings.length; i += 1) {
    const string = strings[i];
    capitalizedStrings.push(string.toUpperCase());
}

console.log(capitalizedStrings);

In this snippet, we start with an array of lowercase names. Then, we initialize an empty array, in which we’ll store our capitalized strings.

在此代码段中,我们从一个小写名称数组开始。 然后,我们初始化一个空数组,在其中存储大写的字符串。

Inside of the for loop, we grab the next string on every iteration; capitalize it; and push it into capitalizedStrings. At the end of the loop, capitalizedStrings contains every word in strings, but…You know, capitalized.

for循环内,每次迭代都获取下一个字符串; 大写; 并将其推送到capitalizedStrings 。 在循环的最后, capitalizedStrings strings包含strings中的每个单词,但是…,大写。

This brings us to our first function: forEach. This is a method on arrays that “automatically” loops through the list for us. In other words, it handles the details of initializing and incrementing a counter for us.

这将我们带到我们的第一个功能: forEach 。 这是对阵列的一种方法,可为我们“自动”遍历列表。 换句话说,它我们处理初始化和递增计数器的细节。

Instead of the above, where we manually index into strings, we can call forEach, and receive the next string on every iteration. The updated version would look something like:

代替上面的方法,我们在其中手动索引为strings ,我们可以调用forEach ,并在每次迭代时接收下一个字符串。 更新后的版本如下所示:

const strings = ['arielle', 'are', 'you', 'there'];
const capitalizedStrings = [];

strings.forEach(function (string) {
    capitalizedStrings.push(string.toUpperCase());
})

This is almost the same as what we started with. But getting rid of that i makes our code more readable.

这与我们开始时几乎相同。 但摆脱那i让我们的代码更易读。

This also introduces a major pattern we’ll see time and time again. Namely: We prefer to use methods on Array.prototype that abstract away details like initializing and incrementing counters. That way, we can focus on the important logic, rather than the boilerplate.

这也引入了一种主要模式,我们将一次又一次看到。 即:我们更喜欢在Array.prototype上使用抽象化细节的方法,例如初始化和递增计数器。 这样,我们可以专注于重要的逻辑,而不是样板。

了解凯撒密码和蛮力 (Understanding the Caesar Cipher and Brute Force)

In the snippets below, we’ll use encrypting and decrypting strings in our examples of map, reduce, and filter.

在下面的代码片段中,我们将在mapreducefilter示例中使用加密和解密字符串。

For example:

例如:

// Thanks to EvanHahn for this: https://gist.github.com/EvanHahn/2587465
const caesar = require('./caesar');

// We can encrypt the string: 'this is my secret message' with `caesar`
// Here, we scramble the message by shifting each letter forward by 2 letters: 'a' becomes 'c'; 's' becomes  'u'; etc.
const encryptedString = caesar('this is my super secret message.', 2);
console.log(encryptedString); // 'vjku ku oa uwrgt ugetgv uvtkpi.'

The idea is that, if I send you a normal message, like 'this is my super secret message', and someone else gets their hands on it, they can read the secret immediately. This obviously sucks if you’re sending sensitive information, like passwords, which someone might be listening for.

这个想法是,如果我向您发送一条普通消息,例如'this is my super secret message' ,并且有人得到了帮助,他们可以立即读取该机密。 如果您正在发送敏感信息(例如密码),而有人可能正在监听这些信息,这显然很糟糕。

Encryp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值