javascript指南_JavaScript还原方法指南

 2023-09-06 阅读 22 评论 0

摘要:javascript指南by Josh Pitzalis 通过乔什皮茨卡利斯(Josh Pitzalis) JavaScript的Reduce方法的工作原理,使用时间以及它可以完成的一些出色工作 (How JavaScript’s Reduce method works, when to use it, and some of the cool things it can do) JavaScript’s redu

javascript指南

by Josh Pitzalis

通过乔什·皮茨卡利斯(Josh Pitzalis)

JavaScript的Reduce方法的工作原理,使用时间以及它可以完成的一些出色工作 (How JavaScript’s Reduce method works, when to use it, and some of the cool things it can do)

JavaScript’s reduce method is one of the cornerstones of functional programming. Let’s explore how it works, when you should use it, and some of the cool things it can do.

JavaScript的reduce方法是函数式编程的基石之一。 让我们探讨一下它的工作原理,何时使用它,以及它可以做的一些很酷的事情。

基本减少 (A Basic Reduction)

Use it when: You have an array of amounts and you want to add them all up.

在以下情况下使用它 :您有一系列金额,想要将它们全部加起来。

const euros = [29.76, 41.85, 46.5];const sum = euros.reduce((total, amount) => total + amount); sum // 118.11

How to use it:

如何使用它:

  • In this example, Reduce accepts two parameters, the total and the current amount.

    在此示例中,Reduce接受两个参数,合计和当前金额。
  • The reduce method cycles through each number in the array much like it would in a for-loop.

    reduce方法在数组中的每个数字之间循环,就像在for循环中那样。
  • When the loop starts the total value is the number on the far left (29.76) and the current amount is the one next to it (41.85).

    循环开始时,总值是最左边的数字(29.76),当前数量是其旁边的数字(41.85)。
  • In this particular example, we want to add the current amount to the total.

    在此特定示例中,我们想将当前金额添加到总计中。
  • The calculation is repeated for each amount in the array, but each time the current value changes to the next number in the array, moving right.

    对数组中的每个数量重复进行计算,但是每次当前值更改为数组中的下一个数字,即向右移动。
  • When there are no more numbers left in the array the method returns the total value.

    当数组中没有剩余数字时,该方法将返回总值。

JavaScript中Reduce方法的ES5版本 (The ES5 version of the Reduce Method In JavaScript​)

If you have never used ES6 syntax before, don’t let the example above intimidate you. It’s exactly the same as writing:

如果您以前从未使用过ES6语法,请不要让上面的示例吓到您。 它与写作完全相同:

var euros = [29.76, 41.85, 46.5]; var sum = euros.reduce( function(total, amount){return total + amount
});sum // 118.11

We use const instead of var and we replace the word function with a “fat arrow” (=>) after the parameters, and we omit the word ‘return’.

我们使用const代替var并在参数后用“胖箭头”( => )替换单词function ,并省略单词“ return”。

I’ll use ES6 syntax for the rest of the examples, since it’s more concise and leaves less room for errors.

在其余的示例中,我将使用ES6语法,因为它更简洁,并且出错的空间更少。

在JavaScript中使用reduce方法求平均值 (Finding an Average with the Reduce Method In JavaScript​)

Instead of logging the sum, you could divide the sum by the length of the array before you return a final value.

除了记录总和,您还可以在将其返回最终值之前将总和除以数组的长度。

The way to do this is by taking advantage of the other arguments in the reduce method. The first of those arguments is the index. Much like a for-loop, the index refers to the number of times the reducer has looped over the array. The last argument is the array itself.

这样做的方法是利用reduce方法中的其他参数。 这些参数中的第一个是索引 。 就像for循环一样,索引指的是reducer在数组上循环的次数。 最后一个参数是数组本身。

const euros = [29.76, 41.85, 46.5];const average = euros.reduce((total, amount, index, array) => {total += amount;if( index === array.length-1) { return total/array.length;}else { return total;}
});average // 39.37

映射和过滤为约简 (Map and Filter as Reductions)

If you can use the reduce function to spit out an average then you can use it any way you want.

如果您可以使用reduce函数吐出一个平均值,那么您可以使用任意方式使用它。

For example, you could double the total, or half each number before adding them together, or use an if statement inside the reducer to only add numbers that are greater than 10. My point is that the Reduce Method In JavaScript​ gives you a mini CodePen where you can write whatever logic you want. It will repeat the logic for each amount in the array and then return a single value.

例如,你可以加入他们在一起之前,总还是各占一半数量增加一倍,或者使用if语句减速里面只有添加大于10我的观点是,reduce方法在JavaScript中给你一个小数字CodePen,您可以在其中编写所需的任何逻辑。 它将对数组中的每个数量重复逻辑,然后返回单个值。

The thing is, you don’t always have to return a single value. You can reduce an array into a new array.

问题是,您不必总是返回单个值。 您可以将一个数组简化为一个新数组。

For instance, lets reduce an array of amounts into another array where every amount is doubled. To do this we need to set the initial value for our accumulator to an empty array.

例如,让我们将金额数组简化为另一个数组,其中每个金额都加倍。 为此,我们需要将累加器的初始值设置为一个空数组。

The initial value is the value of the total parameter when the reduction starts. You set the initial value by adding a comma followed by your initial value inside the parentheses but after the curly braces (bolded in the example below).

初始值是还原开始时总参数的值。 您可以通过在括号内但在花括号后( 在下面的示例中以黑体显示 )后添加一个逗号和您的初始值来设置初始值。

const average = euros.reduce((total, amount, index, array) => {total += amountreturn total/array.length
}, 0);

In previous examples, the initial value was zero so I omitted it. By omitting the initial value, the total will default to the first amount in the array.

在前面的示例中,初始值为零,因此我省略了它。 通过省略初始值, 总计将默认为数组中的第一个值。

By setting the initial value to an empty array we can then push each amount into the total. If we want to reduce an array of values into another array where every value is doubled, we need to push the amount * 2. Then we return the total when there are no more amounts to push.

通过将初始值设置为空数组,我们可以将每个数量推入总计中 。 如果要将值数组简化为每个值都加倍的另一个数组,则需要推入数量 *2。然后在没有更多要推入的数量时返回总数。

const euros = [29.76, 41.85, 46.5];const doubled = euros.reduce((total, amount) => {total.push(amount * 2);return total;
}, []);doubled // [59.52, 83.7, 93]

We’ve created a new array where every amount is doubled. We could also filter out numbers we don’t want to double by adding an if statement inside our reducer.

我们创建了一个新数组,其中每个数量都加倍。 我们还可以通过在化简器中添加if语句来过滤掉不想加倍的数字。

const euro = [29.76, 41.85, 46.5];const above30 = euro.reduce((total, amount) => {if (amount > 30) {total.push(amount);}return total;
}, []);above30 // [ 41.85, 46.5 ]

These operations are the map and filter methods rewritten as a reduce method.

这些操作是作为reduce方法重写的mapfilter方法。

For these examples, it would make more sense to use map or filter because they are simpler to use. The benefit of using reduce comes into play when you want to map and filter together and you have a lot of data to go over.

对于这些示例,使用地图或过滤器会更有意义,因为它们更易于使用。 当您要一起映射和过滤并且需要处理大量数据时,使用reduce的好处就会发挥作用。

If you chain map and filter together you are doing the work twice. You filter every single value and then you map the remaining values. With reduce you can filter and then map in a single pass.

如果将地图链接和筛选器链接在一起,则您需要做两次工作。 您过滤每个值,然后映射其余值。 使用reduce可以过滤,然后一次映射。

Use map and filter but when you start chaining lots of methods together you now know that it is faster to reduce the data instead.

使用map和filter,但是当您开始将许多方法链接在一起时,您现在知道减少数据的速度更快。

在JavaScript中使用Reduce方法创建提示 (Creating a Tally with the Reduce Method In JavaScript​)

Use it when: You have a collection of items and you want to know how many of each item are in the collection.

在以下情况下使用它 :您有一个项目集合,并且想知道该集合中每个项目有多少个。

const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];const count = fruitBasket.reduce( (tally, fruit) => {tally[fruit] = (tally[fruit] || 0) + 1 ;return tally;
} , {})count // { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }

To tally items in an array our initial value must be an empty object, not an empty array like it was in the last example.

要对数组中的项目进行计数,我们的初始值必须是一个空对象,而不是像上一个示例中那样是一个空数组。

Since we are going to be returning an object we can now store key-value pairs in the total.

由于我们将要返回一个对象,因此我们现在可以将键值对存储在总数中。

fruitBasket.reduce( (tally, fruit) => {tally[fruit] = 1;return tally;
}, {})

On our first pass, we want the name of the first key to be our current value and we want to give it a value of 1.

第一次通过时,我们希望第一个键的名称为当前值,并为其赋予值1。

This gives us an object with all the fruit as keys, each with a value of 1. We want the amount of each fruit to increase if they repeat.

这为我们提供了一个以所有水果为键的对象,每个水果的值为1。我们希望如果重复,每种水果的数量都增加。

To do this, on our second loop we check if our total contain a key with the current fruit of the reducer. If it doesn’t then we create it. If it does then we increment the amount by one.

为此,在第二个循环中,我们检查总数是否包含带有减速器当前结果的键。 如果没有,那么我们创建它。 如果是,那么我们将金额增加一。

fruitBasket.reduce((tally, fruit) => {if (!tally[fruit]) {tally[fruit] = 1;} else {tally[fruit] = tally[fruit] + 1;}return tally;
}, {});

I rewrote the exact same logic in a more concise way up top.

我以更简洁的方式重写了完全相同的逻辑。

在JavaScript中使用Reduce方法展平数组的数组 (Flattening an array of arrays with the Reduce Method In JavaScript​​)

We can use reduce to flatten nested amounts into a single array.

我们可以使用reduce将嵌套量展平为单个数组。

We set the initial value to an empty array and then concatenate the current value to the total.

我们将初始值设置为一个空数组,然后将当前值连接到总数。

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];const flat = data.reduce((total, amount) => {return total.concat(amount);
}, []);flat // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

More often than not, information is nested in more complicated ways. For instance, lets say we just want all the colors in the data variable below.

通常,信息以更复杂的方式嵌套。 例如,假设我们只希望下面数据变量中的所有颜色。

const data = [{a: 'happy', b: 'robin', c: ['blue','green']}, {a: 'tired', b: 'panther', c: ['green','black','orange','blue']}, {a: 'sad', b: 'goldfish', c: ['green','red']}
];

We’re going to step through each object and pull out the colours. We do this by pointing amount.c for each object in the array. We then use a forEach loop to push every value in the nested array into out total.

我们将逐步遍历每个对象并提取颜色。 我们通过为数组中的每个对象指向amount.c来实现。 然后,我们使用forEach循环将嵌套数组中的每个值压入总计。

const colors = data.reduce((total, amount) => {amount.c.forEach( color => {total.push(color);})return total;
}, [])colors //['blue','green','green','black','orange','blue','green','red']

If we only need unique number then we can check to see of the number already exists in total before we push it.

如果我们只需要唯一的号码,那么我们可以在推送之前检查一下总数是否已经存在。

const uniqueColors = data.reduce((total, amount) => {amount.c.forEach( color => {if (total.indexOf(color) === -1){total.push(color);}});return total;
}, []);uniqueColors // [ 'blue', 'red', 'green', 'black', 'orange']

减少配管 (Piping with Reduce)

An interesting aspect of the reduce method in JavaScript is that you can reduce over functions as well as numbers and strings.

JavaScript中reduce方法一个有趣的方面是,您可以缩小over函数以及数字和字符串。

Let’s say we have a collection of simple mathematical functions. these functions allow us to increment, decrement, double and halve an amount.

假设我们有一些简单的数学函数。 这些功能使我们可以增加,减少,加倍和减半。

function increment(input) { return input + 1;}function decrement(input) { return input — 1; }function double(input) { return input * 2; }function halve(input) { return input / 2; }

For whatever reason, we need to increment, then double, then decrement an amount.

无论出于什么原因,我们都需要先增加,然后再增加一倍,然后再减少一个量。

You could write a function that takes an input, and returns (input + 1) * 2 -1. The problem is that we know we are going to need to increment the amount three times, then double it, then decrement it, and then halve it at some point in the future. We don’t want to have to rewrite our function every time so we going to use reduce to create a pipeline.

您可以编写一个接受输入并返回(input + 1)* 2 -1的函数。 问题在于,我们知道我们需要将数量增加三倍,然后将其增加一倍,然后将其减小,然后在将来的某个时候将其减半。 我们不需要每次都重写函数,因此我们将使用reduce来创建管道。

A pipeline is a term used for a list of functions that transform some initial value into a final value. Our pipeline will consist of our three functions in the order that we want to use them.

管道是一个术语,用于将一些初始值转换为最终值的功能列表。 我们的管道将按照我们想要使用它们的顺序包括我们的三个功能。

let pipeline = [increment, double, decrement];

Instead of reducing an array of values we reduce over our pipeline of functions. This works because we set the initial value as the amount we want to transform.

而不是减少值的数组,我们减少了功能流水线。 之所以有效,是因为我们将初始值设置为要转换的数量。

const result = pipeline.reduce(function(total, func) {return func(total);
}, 1);result // 3

Because the pipeline is an array, it can be easily modified. If we want to decrement something three times, then double it, decrement it , and halve it then we just alter the pipeline.

因为管道是一个数组,所以可以轻松地对其进行修改。 如果我们想减少三倍,然后将其加倍,再减一,再减半,那么我们就改变一下管道。

var pipeline = [increment,increment,increment,double,decrement,halve];

The reduce function stays exactly the same.

减少功能保持完全相同。

避免的愚蠢错误 (Silly Mistakes to avoid)

If you don’t pass in an initial value, reduce will assume the first item in your array is your initial value. This worked fine in the first few examples because we were adding up a list of numbers.

如果您不传递初始值,那么reduce将假设数组中的第一项是初始值。 在前几个示例中,这很好用,因为我们要添加一个数字列表。

If you’re trying to tally up fruit, and you leave out the initial value then things get weird. Not entering an initial value is an easy mistake to make and one of the first things you should check when debugging.

如果您试图积累水果,而忽略了初始值,那么事情就会变得很奇怪。 不输入初始值是一个容易犯的错误,并且是调试时应检查的第一件事。

Another common mistake is to forget to return the total. You must return something for the reduce function to work. Always double check and make sure that you’re actually returning the value you want.

另一个常见的错误是忘记返回总数。 您必须返回一些内容以使reduce函数起作用。 始终仔细检查并确保您实际上在返回所需的值。

Tools, Tips & References

工具,提示与参考

  • Everything in this post came from a fantastic video series on egghead called Introducing Reduce. I give Mykola Bilokonsky full credit and I am grateful to him for everything I now know about using the Reduce Method In JavaScript​. I have tried to rewrite much of what he explains in my own words as an exercise to better understand each concept. Also, it’s easier for me to reference an article, as opposed to a video, when I need to remember how to do something.

    这篇文章中的所有内容均来自一个名为Inducducing Reduce的精彩视频系列。 我对Mykola Bilokonsky表示了高度赞赏,对于我现在知道的有关在JavaScript中使用Reduce方法的一切事情,我深表感谢。 我试图重写他用我自己的话解释的大部分内容,以更好地理解每个概念。 另外,当我需要记住如何做某事时,相对于视频,我更容易参考一篇文章。

  • The MDN Reduce documentation labels what I called a total the accumulator. It is important to know this because most people will refer to it as an accumulator if you read about it online. Some people call it prev as in previous value. It all refers to the same thing. I found it easier to think of a total when I was learning reduce.

    MDN Reduce文档标记了我所说的总计 accumulator 。 了解这一点很重要,因为如果您在线阅读它,大多数人会将其称为累加器。 有人称其为prev ,与先前的值相同 。 都是指同一件事。 当我学习reduce时,我发现更容易想到总数

  • If you would like to practice using reduce I recommend signing up to freeCodeCamp and completing as many of the intermediate algorithms as you can using reduce.

    如果您想练习使用reduce,我建议您注册freeCodeCamp并完成尽可能多的中间算法 。

  • If the ‘const’ variables in the example snippets are new to you I wrote another article about ES6 variables and why you might want to use them.

    如果示例代码片段中的'const'变量对您来说是新的,那么我写了另一篇有关ES6变量以及为什么要使用它们的文章 。

  • I also wrote an article called The Trouble With Loops that explain how to use map() and filter() if the are new to you.

    我还写了一篇名为《 The Trouble With Loops》的文章, 该文章解释了如果您不熟悉 map()和filter(),如何使用它们。

Thanks for reading! If you’d like to be notified when I write a new article please enter your email here.

谢谢阅读! 如果您希望在我撰写新文章时收到通知,请在此处输入您的电子邮件 。

And if you liked the article, please share it on social media so others can find it.

如果您喜欢这篇文章,请在社交媒体上分享,以便其他人可以找到它。

翻译自: https://www.freecodecamp.org/news/reduce-f47a7da511a9/

javascript指南

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/7886.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息