且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从对象数组中获取平均值

更新时间:2023-11-07 14:34:52

尽管有几个答案,但我还是要重点关注我,以提高代码质量:

Despite of having several answers I would like to add mine focusing to improve the code quality:

  1. 您可以在forEach()中使用分解来获取对象的food属性,因为这只是您感兴趣的属性.
  2. 尽管在内部循环中进行划分,但在循环完成后,我们只能执行一次划分操作.当数组很大(成千上万个对象)时,这样可以节省大量计算
  3. 您可以在循环中使用像+=这样的短手来求和.
  4. 您可以在forEach()
  5. 中创建一行代码
  1. You can use destructuring in forEach() to just get the food property of the object as that is only the property you are interested with.
  2. 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)
  3. You can use short hand like += in the loop for summing up the value.
  4. 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);