函数式编程中用于操作数组的方法就像“毒品”一样,它让很多人爱上函数式编程。因为它们真的十分常用而且又超级简单。 .map()
和 .filter()
都仅需一个参数,该参数定义操作数组每一个元素的函数即可。reduce()
会复杂一些,我之前写过一篇文章介绍为什么人们难以掌握reduce()
方法,其中一个原因在于很多入门资料都仅仅用算术作为例子。我写了很多用reduce()
来做算术以外的例子。
用reduce()
来计算数组的平均值是一个常用的模式。代码看起来非常简单,不过在计算最终结果之前你需要做两个准备工作:
- 数组的长度
- 数组所有元素之和
这两个事情看起来都很简单,那么计算数组的平均值并不是很难了吧。解法如下:
function average(nums) {
return nums.reduce((a, b) => a + b) / nums.length;
}
复制代码
确实不是很难,是吧?但是如果数据结构变得复杂了,就没那么简单了。比如,数组里面的元素是对象,你需要先过滤掉某些对象,然后从对象中取出数字。这样的场景让计算平均值变得复杂了一点。
接下来我们处理一个类似的问题(从this Free Code Camp challenge获得灵感),我们会提供 5 种不同的解法,每一种方法有各自的优点和缺点。这 5 种方法也展示了 JavaScript 的灵活。我希望可以给你在使用reduce
的实战中一些灵感。
问题提出
假设我们有一个数组,记录了维多利亚时代常用的口语。接下来我们要找出那些依然现存于 Google Books 中的词汇,并计算他们的平均流行度。数据的格式是这样的:
const victorianSlang = [
{
term: "doing the bear",
found: true,
popularity: 108
},
{
term: "katterzem",
found: false,
popularity: null
},
{
term: "bone shaker",
found: true,
popularity: 609
},
{
term: "smothering a parrot",
found: false,
popularity: null
},
{
term: "damfino",
found: true,
popularity: 232
},
{
term: "rain napper",
found: false,
popularity: null
},
{
term: "donkey’s breakfast",
found: true,
popularity: 787
},
{
term: "rational costume",
found: true,
popularity: 513
},
{
term: "mind the grease",
found: true,