我试图从数组中排除“ 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);
}
守着星空守着你
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);
添加回答
举报
0/150
提交
取消