我有一个可以在更新数据时激活的功能,我需要让它计算统计数据的新平均值。
这是我需要更改的代码,添加新用户后它会更新统计信息:
if (statistic !== null && statistic !== undefined) {
let beforeLogParticipators = statistic.totalParticipation;
let averageEnergy = statistic.averageEnergy;
let averageEnjoyment = statistic.averageEnjoyment;
if (beforeLogParticipators !== 0) {
averageEnergy = averageEnergy * beforeLogParticipators;
averageEnjoyment = averageEnjoyment * beforeLogParticipators
}
let afterLogParticipators = beforeLogParticipators + 1;
let newAverageEnergy = (averageEnergy + newLog.energy) / afterLogParticipators;
let newAverageEnjoyment = (averageEnjoyment + newLog.enjoyment) / afterLogParticipators;
let newAverage = (newAverageEnergy + newAverageEnjoyment) / 2;
let numberOfTeamMembers = statistic.totalMembers;
let participationRate = (afterLogParticipators * 100) / numberOfTeamMembers;
let newStatisticObject = {
totalMembers: numberOfTeamMembers,
participationRate: participationRate,
averageEnergy: newAverageEnergy,
averageEnjoyment: newAverageEnjoyment,
averageStat: newAverage,
totalParticipation: afterLogParticipators,
};
我已经尝试了所有我知道的东西,但是无法正常工作。
不起作用的示例:
if (statistic !== null && statistic !== undefined) {
let newAverageEnergy = (oldStatistic.averageEnergy + statistic.averageEnergy) / 2;
let newAverageEnjoyment = (oldStatistic.averageEnjoyment + statistic.averageEnjoyment) / 2;
let newAverage = (newAverageEnergy + newAverageEnjoyment) / 2;
let newStatisticObject = {
averageEnjoyment: newAverageEnjoyment,
averageEnergy: newAverageEnergy,
averageStat: newAverage,
};