gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:15:07 24 4
gpt4 key购买 nike

我试图从数组中排除“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

最佳答案

先过滤掉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);
}

关于javascript - 计算平均值时如何从数组中排除零值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55660452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com