首页 > 解决方案 > 我可以不使用 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;
}

我只是一个初学者,我正在训练做正确的事情。因此,我将感谢您的所有帮助。谢谢。

标签: javascriptforeachreduce

解决方案


是的。替换这个:

  let starRatingAVG = 0;
  postComments.forEach(comment => {
    starRatingAVG = starRatingAVG + comment.starRating
  })

有了这个:

  let starRatingAVG = postComments.reduce((acc, x) => acc + x.starRating, 0);

推荐阅读