亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算平均值時如何從數組中排除零值?

計算平均值時如何從數組中排除零值?

UYOU 2021-04-06 17:17:50
我試圖從數組中排除“ 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
查看完整描述

2 回答

?
catspeake

TA貢獻1111條經驗 獲得超0個贊

只需先過濾掉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);

}


查看完整回答
反對 回復 2021-04-29
?
守著星空守著你

TA貢獻1799條經驗 獲得超8個贊

可以將函數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);


查看完整回答
反對 回復 2021-04-29
  • 2 回答
  • 0 關注
  • 279 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號