【问题标题】:access the array object inside a higher order function访问高阶函数内的数组对象
【发布时间】:2018-02-26 01:13:52
【问题描述】:

我正在尝试访问我在该 reduce 中使用 reduce 函数的数组的长度,但我似乎无法做到这一点,有没有人知道是否可以访问任何高阶函数中的数组对象?

PS:我尝试使用this,但没有成功;

PSS:我想使用 reduce 函数计算平均评分,所以我使用 reduce 对数组中的所有值求和,然后将这些相同的值除以数组长度,如下所示:

let averageRating = watchList
    .filter(movie => movie.Director === 'Christopher Nolan')
    .map(x => parseFloat(x.imdbRating))
    .reduce((total, current) => total + (current / 'array length'));

你猜对了,“数组长度”是数组长度。

PSSS:尝试过

var averageRating = watchList
  .filter(movie => movie.Director === 'Christopher Nolan')
  .map(x => parseFloat(x.imdbRating))
  .reduce((total, current, index, arr) => total + (current / arr.length));

但数组长度会随着数组的减少而不断变化,因此它不适用于我的目的。

【问题讨论】:

  • 请分享您的一些代码。如果您有代码,则更容易为您提供帮助。
  • 如果你在reduce之前将它分配给一个var并使用它?
  • 我可以这样做,但我真的很想找到一种在 reduce 中访问它的方法,但似乎不可能:(
  • reduce 提供了四个参数:累加器、当前数组值、它的索引和数组本身。如果你给你的回调四个参数,最后一个将是数组,你可以得到它的长度。

标签: javascript arrays higher-order-functions


【解决方案1】:

应该这样做:

let averageRating = watchList
    .filter(movie => movie.Director === 'Christopher Nolan')
    .map(x => parseFloat(x.imdbRating))
    .reduce((total, current, idx, arr) => total + (current / arr.length));

更新

如果您有兴趣了解我将如何在我的首选库中执行此操作,Ramda(免责声明:我是其主要作者之一)代码如下所示:

const {pipe, filter, propEq, pluck, map, mean} = R;

const watchList = [{"Director": "Christopher Nolan", "imdbRating": 4.6, "title": "..."}, {"Director": "Michel Gondry", "imdbRating": 3.9, "title": "..."}, {"Director": "Christopher Nolan", "imdbRating": 2.8, "title": "..."}, {"Director": "Christopher Nolan", "imdbRating": 4.9, "title": "..."}, {"Director": "Alfred Hitchcock", "imdbRating": 4.6, "title": "..."}, {"Director": "Christopher Nolan", "imdbRating": 4.6, "title": "..."}];

const averageRating = pipe(
  filter(propEq('Director', 'Christopher Nolan')),
  pluck('imdbRating'),
  map(Number),
  mean
);

console.log(averageRating(watchList));
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

我发现这会产生非常干净、可读的代码。

【讨论】:

  • 我试过了,但是我需要数组长度作为一个常数,它会随着数组的减少而变化,所以最后的平均值是错误的。
  • reduce 不会自行更改数组。是什么改变了它?
  • 没关系。我仍在试图弄清楚你的情况发生了什么。您能否提供有关更改阵列的详细信息?是不是类似数组但不是数组的其他数据结构(类似于NodeListarguments)?
  • 你说得对,我只是在做一些测试,并认为如果我没有给出初始值 0,那么平均值最终会是预期值的两倍
  • 只需添加 initialValue 即可为我修复它。
【解决方案2】:

你可以试试这个:

let averageRating = watchList
        .filter(movie => movie.Director === 'Christopher Nolan')
        .map(x => parseFloat(x.imdbRating))
        .reduce((total, current, index, array) => {
            total += current;
            if( index === array.length - 1) {
               return total/array.length;
            } else {
               return total;
            }
        });

【讨论】:

  • 这也可以,但出于某种原因,我想将每个值除以长度以减少行数,但谢谢:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多