javascript - 我可以不使用 forEach() 而是使用 .reduce() 来使这个函数更干净吗?
问题描述
我可以不使用 forEach() 而是使用 .reduce() 来使这个函数更干净吗?
const post = [
{
id: "1",
dateOfPost: "15.10.2020",
postTitle: "...",
postText: "...",
},
comments: [
{
id: "1",
dateOfComment: "15.10.2020",
gravatar: "...",
nicName: "...",
commentText: "...",
starRating: 3,
likeCount: 8,
dislikeCount: 1
},
{
id: "2",
dateOfComment: "15.10.2020",
gravatar: "...",
nicName: "...",
commentText: "...",
starRating: 5,
likeCount: 1,
dislikeCount: 1
},
]
}
];
const postComments = post[0].comments;
const starRatingAverage = () => {
let starRatingAVG = 0;
postComments.forEach(comment => {
starRatingAVG = starRatingAVG + comment.starRating
})
return starRatingAVG = starRatingAVG / postComments.length;
}
我只是一个初学者,我正在训练做正确的事情。因此,我将感谢您的所有帮助。谢谢。
解决方案
是的。替换这个:
let starRatingAVG = 0;
postComments.forEach(comment => {
starRatingAVG = starRatingAVG + comment.starRating
})
有了这个:
let starRatingAVG = postComments.reduce((acc, x) => acc + x.starRating, 0);
推荐阅读
- php - 浮动到字符串部分工作,为什么(字符串)在 PHP 中将 0.999999999999999 舍入为 1?
- tensorflow - 在 tensorflow 估计器中创建自定义指标
- pycharm - 如何阻止 PyCharm 中的文本粗细发生变化?
- kubernetes - 如何将新的配置参数/标志应用到 etcd 服务器
- python - binary_dilation 的反面
- unit-testing - 带 xUnit 的 Moq 和 AutoMoq (AutoFixture) 的依赖注入
- python - 子进程如何决定将什么编码写入仅接受 str 的文件对象
- python - Python:如何从 Selenium 的下拉菜单中选择选项,隐藏元素
- javascript - 如何模拟在使用 Jest 测试的 React 组件中进行的 API 调用
- excel - 如何从 Excel vba 更改 Word 页脚的变量?