下面,我重现我的代码以计算食物的平均评分。
3 + 4 + 5 + 2/4应该等于3.5。 但这不能给我正确的输出。我的代码有什么问题?
const ratings = [
{food:3},
{food:4},
{food:5},
{food:2}
];
let food = 0;
ratings.forEach((obj,index)=>{
food = (food + obj.food)/++index
})
console.log("FOOD",food)
任何帮助!
感谢进阶!
答案 0 :(得分:3)
尽管有几个答案,但我想重点关注我,以提高代码质量:
forEach()
中使用解构来获取对象的food
属性,因为这只是您感兴趣的属性。+=
这样的短手来求和。forEach()
中创建一行代码
const ratings = [
{food:3},
{food:4},
{food:5},
{food:2}
];
let foodTotal = 0;
let length = ratings.length;
ratings.forEach(({food})=> foodTotal += food);
console.log("FOOD",foodTotal/length);
答案 1 :(得分:1)
您需要将相对贡献值添加到每种食物的平均值中。
由于平均值为-项目总和/根据您的情况为
values.newfield
我们可以拆分为
(3+4+5+2) / 4
3/4 + 4/4 + 5/4 + 2/4
您也可以使用const ratings = [{"food":3},{"food":4},{"food":5},{"food":2}];
let food = 0;
ratings.forEach((obj) => {
food = food + obj.food / ratings.length;
})
console.log("FOOD", food)
来缩短代码:
Array.reduce()
答案 2 :(得分:1)
将元素相加后,需要除以元素数
const ratings = [
{food:3},
{food:4},
{food:5},
{food:2}
];
let food = 0;
ratings.forEach((obj,index)=>{
food = (food + obj.food)
});
food = food / ratings.length;
console.log("FOOD",food)
答案 3 :(得分:1)
您将使用reduce求和,然后简单地除以评级的长度
const ratings = [
{food:3},
{food:4},
{food:5},
{food:2}
];
const avg = ratings.reduce((a, {food}) => a + food, 0) / ratings.length;
console.log(avg);
答案 4 :(得分:1)
这是另一个使用.reduce()的解决方案
const ratings = [
{food: 3},
{food: 4},
{food: 5},
{food: 2}
]
const average = ratings.reduce((a, b) => {
return {food: a.food + b.food}
}).food / ratings.length
console.log('FOOD', average)
答案 5 :(得分:0)
您正在做的是vgImage
,它不等同于3/1 + 4/2 + 5/3 + 2/4
。
3/4 + 4/4 + 5/4 + 2/4
如果您正在使用功能性的方法,那么我将使用reduce函数来获取结果。
ratings.forEach((obj,index)=>{
food = (food + obj.food)
});
food = food / ratings.length;
console.log("FOOD",food)