计算平均值时如何从数组中排除零值?

我试图从数组中排除“ 0”值,以获得更好的平均结果。


我的数组是:[0,0,0,0,80,90,100,0]



function clacGPA(gradeData) {

  var sum, avg = 0;


  if (gradeData.length) {

    sum = gradeData.reduce(function (a, b) {

      return a + b;

    });

    avg = sum / gradeData.length;

  }

  document.getElementById('gpa').innerText = avg.toFixed(2);

}



My expected result should be:

avg = 80+90+100 / 3


UYOU
浏览 242回答 2
2回答

catspeake

只需先过滤掉0个值:clacGPA([0, 0, 0, 0, 80, 90, 100, 0]);function clacGPA(gradeData) {  const filtered = gradeData.filter(item => item !== 0);  const sum = filtered.reduce((a, b) => a + b);  const avg = sum / filtered.length;  console.log(avg);}

守着星空守着你

可以将函数reduce与累加器一起使用,该累加器存储计数和总和。let arr = [0, 0, 0, 0, 80, 90, 100, 0];let result = arr.reduce((a, c) => {  if (c !== 0) {    a.count++;    a.sum += c;  }    return a;}, {count: 0, sum: 0});if (result.count) console.log(result.sum / result.count);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript