by Guido Schmitz

由Guido Schmitz

Higher order functions can help you to step up your JavaScript game by making your code more declarative. That is, short, simple, and readable.

高阶函数可以通过使代码更具声明性来帮助您增强JavaScript游戏。 即,简短,简单且可读。

A Higher Order Function is any function that returns a function when executed, takes a function as one or more of its arguments, or both. If you have used any of the Array methods like map or filter, or passed a callback function to jQuery’s $.get, you have already worked with Higher Order Functions.

高阶函数是在执行时返回函数,将一个函数用作其一个或多个参数或两者兼有的任何函数。 如果您使用了诸如mapfilter任何Array方法,或者将回调函数传递给jQuery的$.get ,那么您已经使用了高阶函数。

When you use Array.map, you provide a function as its only argument, which it applies to every element contained in the array.

当您使用Array.map ,您将提供一个函数作为其唯一参数,该函数适用于数组中包含的每个元素。

var arr = [ 1, 2, 3 ];var arrDoubled = arr.map(function(num) {return num * 2;
});console.log(arrDoubled); // [ 2, 4, 6 ]

Higher order functions can also return a function. For example, you can make a function called multiplyBy that takes a number and returns a function that multiplies another number you provide by the first number provided. You can use this approach to create a multiplyByTwo function to pass to Array.map. This will give you the same result you saw above.

高阶函数也可以返回一个函数。 例如,您可以使一个名为multiplyBy的函数接受一个数字,然后返回一个函数,该函数将您提供的另一个数字乘以提供的第一个数字。 您可以使用此方法来创建一个multiplyByTwo功能传递给Array.map 。 这将为您提供与上述相同的结果。

function multiplyBy(num1) {return function(num2) {return num1 * num2;}
}var multiplyByTwo = multiplyBy(2);var arr = [ 1, 2, 3 ];var arrDoubled = arr.map(multiplyByTwo);console.log(arrDoubled); // [ 2, 4, 6 ]

Knowing when and how to use these functions is essential. They make your code easier to understand and maintain. It also makes it easy to combine functions with each other. This is called composition, and I will not go in much detail here. In this article I will cover the three most used higher order functions in JavaScript. These are .filter(), .map() and .reduce().

了解何时以及如何使用这些功能至关重要。 它们使您的代码更易于理解和维护。 它还使相互组合功能变得容易。 这称为合成,在此不再赘述。 在本文中,我将介绍JavaScript中三个最常用的高阶函数。 这些都是.filter() .map().reduce()

过滤 (Filter)

Imagine writing a piece of code that accepts a list of people where you want to filter out the people that are equal or above the age of 18.

想象一下,编写一段代码来接受要过滤掉年龄等于或大于18岁的人员的人员列表。

Our list looks like the one below:

我们的列表如下所示:

const people = [ { name: ‘John Doe’, age: 16 }, { name: ‘Thomas Calls’, age: 19 }, { name: ‘Liam Smith’, age: 20 }, { name: ‘Jessy Pinkman’, age: 18 },];

Let’s look at an example of a first order function which select people that are above the age of 18. I’m using an arrow function that is part of the ECMAScript standard or ES6 for short. It’s just a shorter way of defining a function and allows you to skip typing function and return, as well as some parentheses, braces, and a semicolon.

让我们看一下选择18岁以上人群的一阶函数的示例。我使用的箭头函数是ECMAScript标准或ES6的一部分。 这只是定义函数的一种较短方法,它允许您跳过键入函数并返回,以及一些括号,花括号和分号。

const peopleAbove18 = (collection) => {  const results = [];   for (let i = 0; i < collection.length; i++) {    const person = collection[i];     if (person.age >= 18) {      results.push(person);    }  }
return results;};

Now what if we want to select all the people who are between 18 and 20? We could create another function.

现在,如果我们要选择18至20岁之间的所有人,该怎么办? 我们可以创建另一个函数。

const peopleBetween18And20 = (collection) => {  const results = [];   for (let i = 0; i < collection.length; i++) {    const person = collection[i];     if (person.age >= 18 && person.age <= 20) {      results.push(person);    }  }
return results;};

You may already recognize a lot of repeating code here. This could be abstracted into a more generalized solution. These two functions have something in common. They both iterate over a list and filter it on a given condition.

您可能已经在这里认识到很多重复的代码。 这可以抽象为更通用的解决方案。 这两个功能有一些共同点。 它们都遍历列表,并在给定条件下对其进行过滤。

“A higher order function is a function that takes one or more functions as arguments.”— Closurebridge

“高阶函数是将一个或多个函数作为参数的函数。” — Closurebridge

We can improve our previous function by using a more declarative approach, .filter().

我们可以使用更具声明性的方法.filter()来改进先前的功能。

const peopleAbove18 = (collection) => {  return collection    .filter((person) => person.age >= 18);}

That’s it! We can reduce a lot of extra code by using this higher order function. It also make our code better to read. We don’t care how things are being filtered, we just want it to filter. I will go into combining functions later in this article.

而已! 通过使用此高阶函数,我们可以减少很多额外的代码。 这也使我们的代码更易于阅读。 我们不在乎如何过滤事物,我们只希望它进行过滤。 我将在本文的后面部分介绍合并功能。

地图 (Map)

Let’s take the same list of people and an array of names that tells if the person loves to drink coffee.

让我们以相同的人员列表和一组名称来说明该人员是否喜欢喝咖啡。

const coffeeLovers = [‘John Doe’, ‘Liam Smith’, ‘Jessy Pinkman’];

The imperative way will be like:

命令式如下:

const addCoffeeLoverValue = (collection) => {  const results = [];   for (let i = 0; i < collection.length; i++) {    const person = collection[i];
if (coffeeLovers.includes(person.name)) {      person.coffeeLover = true;    } else {      person.coffeeLover = false;    }     results.push(person);  }   return results;};

We could use .map() to make this more declarative.

我们可以使用.map()使其更具说明性。

const incrementAge = (collection) => {  return collection.map((person) => {    person.coffeeLover = coffeeLovers.includes(person.name);     return person;  });};

Again, .map() is a high-order function. It allows a function to be passed as an argument.

同样, .map()是一个高阶函数。 它允许将函数作为参数传递。

减少 (Reduce)

I bet you will like this function when you know when and how to use it.The cool thing about .reduce() is that most of the functions above can be made with it.

我敢打赌,当您知道何时以及如何使用它时,您将喜欢此函数.reduce()在于,上面的大多数函数都可以使用它来完成。

Let’s take a simple example first. We want to sum up all the people’s ages. Again, we’ll look how this can be done using the imperative approach. It’s basically looping through the collection and increment a variable with the age.

首先让我们举一个简单的例子。 我们要总结全体人民的年龄。 再次,我们将探讨如何使用命令式方法来完成此任务。 它基本上是遍历整个集合,并随年龄增长一个变量。

const sumAge = (collection) => {  let num = 0;   collection.forEach((person) => {    num += person.age;  });   return num;}

And the declarative approach using .reduce().

以及使用.reduce()的声明方法。

const sumAge = (collection) => collection.reduce((sum, person) => { return sum + person.age;}, 0);

We can even use .reduce() to create our own implementation of .map() and .filter() .

我们甚至可以使用.reduce()创建我们自己的.map().filter()

const map = (collection, fn) => {  return collection.reduce((acc, item) => {    return acc.concat(fn(item));  }, []);}
const filter = (collection, fn) => {  return collection.reduce((acc, item) => {    if (fn(item)) {      return acc.concat(item);    }     return acc;  }, []);}

This might be hard to understand at first. But what .reduce() basically does is start with a collection and a variable with an initial value. You then iterate over the collection and append (or add) the values to the variable.

起初这可能很难理解。 但是.reduce()基本上是从一个集合和一个带有初始值的变量开始的。 然后,您遍历集合并将值附加(或添加)到变量。

结合地图,过滤和缩小 (Combining map, filter and reduce)

Great, that these functions exist. But the good part is that they exist on the Array prototype in JavaScript. This means these functions can be used together! This makes it easy to create reusable functions and reduce the amount of code that is required to write certain functionality.

太好了,这些功能存在。 但是好消息是它们存在于JavaScript的Array原型中。 这意味着这些功能可以一起使用! 这样可以轻松创建可重用的功能,并减少编写某些功能所需的代码量。

So we talked about using .filter() to filter out the people that are equal or below the age of 18. .map() to add the coffeeLover property, and .reduce() to finally create a sum of the age of everyone combined.Lets write some code that actually combines these three steps.

因此,我们讨论了使用.filter()过滤掉等于或小于18岁的用户coffeeLover .map()添加了coffeeLover属性,而coffeeLover .reduce()最终创建了每个人的总和让我们编写一些实际上结合了这三个步骤的代码。

const people = [ { name: ‘John Doe’, age: 16 }, { name: ‘Thomas Calls’, age: 19 }, { name: ‘Liam Smith’, age: 20 }, { name: ‘Jessy Pinkman’, age: 18 },];
const coffeeLovers = [‘John Doe’, ‘Liam Smith’, ‘Jessy Pinkman’];
const ageAbove18 = (person) => person.age >= 18;const addCoffeeLoverProperty = (person) => { person.coffeeLover = coffeeLovers.includes(person.name);  return person;}
const ageReducer = (sum, person) => { return sum + person.age;}, 0);
const coffeeLoversAbove18 = people .filter(ageAbove18) .map(addCoffeeLoverProperty);
const totalAgeOfCoffeeLoversAbove18 = coffeeLoversAbove18 .reduce(ageReducer);
const totalAge = people .reduce(ageReducer);

If you do it the imperative way, you will end up writing a lot of repeating code.

如果以命令方式执行此操作,则最终将编写大量重复的代码。

The mindset of creating functions with .map() ,.reduce() and .filter() will improve the quality of the code you’ll write. But it also adds a lot of readability. You don’t have to think about what’s going on inside a function. It’s easy to understand.

创建的功能与心态.map() .reduce().filter()将提高你写的代码的质量。 但这也增加了很多可读性。 您不必考虑函数内部发生了什么。 很容易理解。

Thanks for reading! :)

谢谢阅读! :)

Say hello on Twitter

在Twitter上问好

翻译自: https://www.freecodecamp.org/news/higher-order-functions-in-javascript-d9101f9cf528/

高阶函数:如何使用过滤器,映射和约简以获得更可维护的代码相关推荐

  1. 【Kotlin】Kotlin 语言集合中的高阶函数详解 ( 数据类 data class | maxBy | minBy | filter | map | any | count | find )

    文章目录 I . List 集合高阶函数引入 II . Kotlin 数据类 ( data class ) III . Java 代码 与 Kotlin 代码实现对比 ( 查询年龄最大的 ) IV . ...

  2. Python高阶函数--map、lambda、reduce、filter、zip

    一.map()函数 map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把list 的每个元素依次作用在函数 f 上,得到一个新的 list 并返回. 例如,对于l ...

  3. NLP(9): 机器学习介绍,朴素贝叶斯,python高阶函数应用

    第一节:机器学习 D={X,y} x:特征 y:标签 f:学习x到y的映射关系 1.机器学习定义: 自动从已有的数据里找出一些规律(与专家系统的区别),然后把学到的这些规律应用到对未来数据的预测值,或 ...

  4. Python3进阶--正则表达式、json、logging日志配置、数据库操作、枚举、闭包、匿名函数和高阶函数、time、datetime

    第一章 变量.常用循环体.代码结构.代码练习 第二章 列表.元组等数据结构.字符串驻留机制及字符串格式化操作 第三章 函数.面向对象.文件操作.深浅拷贝.模块.异常及捕获 第四章 项目打包.类和对象高 ...

  5. 【廖雪峰Python学习笔记】高阶函数

    Higher-order function 高阶函数 映射 过滤算法 排序算法 高阶函数 变量可指向函数 >>> abs # 函数 <built-in function abs ...

  6. c2064 项不会计算为接受0个参数的函数_【JS必知必会】高阶函数详解与实战

    本文涵盖 前言 高级函数概念 函数作为参数的高阶函数 map filter reduce sort详解与实战 函数作为返回值的高阶函数 isType函数与add求和函数 如何自己创建高阶函数 前言 一 ...

  7. python中的高阶函数

    python中的高阶函数 文章目录: 1 什么是高阶函数? 1.1 高阶函数:一个函数的`函数名`作为参数传给另外一个函数 1.2 高阶函数:一个函数返回值(return)为另外一个`函数` 2 py ...

  8. python高阶函数

    高阶函数,接收函数作为参数,或者将函数作为返回值的函数是高阶函数: 5个带key内置函数 filter/map(function, iterable) --> 迭代器 sorted(iterab ...

  9. python高阶函数的使用

    1.map Python内建了map()函数,map()函数接受两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每一个元素上,并把结果作为新的Iterator返回. 举 ...

最新文章

  1. 由MessageBox和AfxMessageBox的使用异同所感
  2. 成都理工大学乐千桤java考试_2009年度优秀教师、优秀教务工作者评选结果公示-成都理工大学工会...
  3. CSS上下左右居中的几种方法
  4. pythonweb开发-如何用Python做Web开发?——Django环境配置
  5. Eclipse Collections:让Java Streams更上一层楼
  6. using 指令是不需要的和其他两个C#错误
  7. 再见python你好go语言_再见Shell,你好Python
  8. Spring 通过Java Config方式连接数据库
  9. Android-完美解决在Activity中触摸返回键onBackPressed不能触发问题
  10. 网页html 图片横向摆放,css实现多张图片横向居中显示的方法
  11. keras cnn注意力机制_2019 SSA-CNN(自注意力机制)目标检测算法论文阅读笔记
  12. HDU 2148 Score
  13. [#5YaZ5LiA56+H5rKh5pyJ5Lq66IO955yL5oeC55qE5Y2a5a6i#]
  14. 【numpy】TypeError: only size-1 arrays can be converted to Python scalars
  15. android键盘驱动程序下载,万能键盘驱动程序
  16. 根据IP地址获取地理位置
  17. 本科、硕士和博士有何区别?
  18. 最新php面试题及答案
  19. Hashicorp Vault(金库)
  20. OpenGL学习之材质RGB值和光源RGB值关系

热门文章

  1. 对RAM,ROM,NOR/NAND FLASH等常见内存设备类型的理解
  2. 网站容器化升级---各模块分别运行一个容器
  3. 点亮一盏灯,温暖一个梦
  4. 解决vue项目路由出现message: “Navigating to current location (XXX) is not allowed“的问题
  5. 家用空调什么牌子好又省电质量又好
  6. macOS_Catalina_10.15.7_19H15可引导可虚拟机安装的纯净版苹果OS系统ISO镜像安装包免费下载
  7. 使用手机调试Android软件
  8. JVM语言Xtend优缺点速览
  9. 打印机有重影问题解决方案
  10. win10如何离线安装.NET Framework3.5