本文介绍了如何从对象数组中获取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面,我复制我的代码以计算食物的平均评分.
Below I reproduce my code for calculate average ratings for foods.
3 + 4 + 5 + 2/4应该等于3.5.但这不能给我正确的输出.我的代码有什么问题?
3+4+5+2 / 4 should be equal to 3.5.But this not gives me the correct output. What's wrong with my code?
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)
推荐答案
尽管有几个答案,但我还是要重点关注我,以提高代码质量:
Despite of having several answers I would like to add mine focusing to improve the code quality:
- 您可以在
forEach()
中使用分解来获取对象的food
属性,因为这只是您感兴趣的属性. - 尽管在内部循环中进行划分,但在循环完成后,我们只能执行一次划分操作.当数组很大(成千上万个对象)时,这样可以节省大量计算
- 您可以在循环中使用像
+=
这样的短手来求和. - 您可以在
forEach()
中创建一行代码
- You can use destructuring in
forEach()
to just get thefood
property of the object as that is only the property you are interested with. - Despite of dividing inside loop we can have only one division operation after the loop is completed. This saves a lot of computation when the array is huge(thousands of objects)
- You can use short hand like
+=
in the loop for summing up the value. - You can make a single line code in
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);
这篇关于如何从对象数组中获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!