【发布时间】: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