2 回答
TA贡献1815条经验 获得超10个赞
简单的方法,一步步处理。
const getAverage = (reviews) => {
let TotalStars = reviews.reduce((prev, curr) => (curr.stars + prev), 0)
// TotalStars is 3.6666
// below use any one of them averageStars
// let averageStars = Math.round(TotalStars/reviews.length); // output 4
// let averageStars = Math.floor(TotalStars/reviews.length); // output 3
let averageStars = Math.floor((TotalStars/reviews.length)*10)/10;// output 3.6
return averageStars;
};
<div>
<p className="totalReviewsTally">Average: {getAverage(reviews)} {reviews.length}</p>
</div>
TA贡献1858条经验 获得超8个赞
您忘记return了评论getAverage,我已尝试解决一些问题,如果这仍然不起作用,请告诉我。
根据你的评论
Reviews = [ { "text": "太可爱了,喜欢它!", "stars": 4, "id": 1 }, { "text": "手工制作很可爱,但第一次洗就褪色了。", "stars": 2, "id": 2 }, { "text": "给我最好的朋友的第一个孩子的好礼物。", "stars": 5, "id": 3 } ]
const getAverage = (reviews) => {
return Math.round(reviews.reduce((acc, curr) => (acc + curr.stars), 0) / reviews.length));
};
<div>
<p className="totalReviewsTally">Average: { getAverage(reviews) } {reviews.length}</p>
</div>
添加回答
举报