edm*_*ani 7 javascript arrays higher-order-functions
我正在尝试访问我在其中使用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'));
Run Code Online (Sandbox Code Playgroud)
你猜对了'数组长度',数组长度.
PSSS:试过
var averageRating = watchList
.filter(movie => movie.Director === 'Christopher Nolan')
.map(x => parseFloat(x.imdbRating))
.reduce((total, current, index, arr) => total + (current / arr.length));
Run Code Online (Sandbox Code Playgroud)
但是数组长度随着数组的减少而不断变化,所以它不适用于我的目的.
这应该可以做到:
let averageRating = watchList
.filter(movie => movie.Director === 'Christopher Nolan')
.map(x => parseFloat(x.imdbRating))
.reduce((total, current, idx, arr) => total + (current / arr.length));
Run Code Online (Sandbox Code Playgroud)
如果您有兴趣了解我将如何在我喜欢的库Ramda中执行此操作(免责声明:我是其主要作者之一),代码将如下所示:
let averageRating = watchList
.filter(movie => movie.Director === 'Christopher Nolan')
.map(x => parseFloat(x.imdbRating))
.reduce((total, current, idx, arr) => total + (current / arr.length));
Run Code Online (Sandbox Code Playgroud)
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));Run Code Online (Sandbox Code Playgroud)
我发现这会产生非常干净、可读的代码。