JavaScript如何在reduce计算科目总分时同步计算百分比与绩点
实现方案
直接调整subjectTotal的计算逻辑,把分数累加、百分比/绩点计算整合到同一流程里,不需要后续手动逐个科目调用计算函数,完整代码如下:
const value = { english_1st_CQ: 5, english_2nd_CQ: 10, math_1st_CQ: 15, math_1st_MCQ: 20, math_2nd_CQ: 25, math_2nd_MCQ: 30, }; // 前置百分比、绩点计算函数 const calculatePercentage = (subTotal) => { if (subTotal === 0) return { percentage: 0, GP: 0 }; const percentage = (subTotal / 100) * 100 - 4; let GP; if (percentage >= 80) GP = 5; if (percentage >= 70 && percentage <= 79) GP = 4; if (percentage >= 60 && percentage <= 69) GP = 3.5; if (percentage >= 50 && percentage <= 59) GP = 3; if (percentage >= 40 && percentage <= 49) GP = 2; if (percentage >= 33 && percentage <= 39) GP = 1; if (percentage < 33) GP = 0; return { percentage, GP }; }; const subjectTotal = Object.entries(value).reduce((result, [key, score]) => { const [subjectName, subjectPosition, suffix] = key.split('_') const paperKey = `${subjectName}_${subjectPosition}`; // 初始化单张试卷的累计分 if(!result.papers[paperKey]) { result.papers[paperKey] = 0; } result.papers[paperKey] += score; // 初始化对应大科目的累计分 if(!result.subjects[subjectName]) { result.subjects[subjectName] = { total: 0 }; } result.subjects[subjectName].total += score; return result; }, { papers: {}, subjects: {} }); // 所有分数累加完成后,自动批量计算所有科目的百分比和绩点 Object.values(subjectTotal.subjects).forEach(subject => { const calcRes = calculatePercentage(subject.total); subject.percentage = calcRes.percentage; subject.GP = calcRes.GP; }); console.log(subjectTotal);
核心调整点
- 将
calculatePercentage函数定义前置,避免计算阶段出现函数未定义报错 - 重构reduce的输出结构,拆分两个统计维度:
papers:存储单张试卷(如english_1st、math_2nd)的总分,和原有reduce的输出逻辑完全兼容subjects:存储大科目(如english、math)的汇总数据,累加阶段只统计总分,所有原始分遍历完成后自动遍历所有大科目调用计算函数,补全百分比、绩点字段
- 完全移除手动编写
math_percentage、english_percentage的重复代码,后续新增科目时只要原始分key保持科目_场次_题型的命名规则,就会自动完成全量计算,无需修改统计逻辑
如果需要单张试卷维度也附带百分比、绩点数据,在现有代码末尾追加以下逻辑即可:
Object.entries(subjectTotal.papers).forEach(([paperKey, total]) => { const calcRes = calculatePercentage(total); subjectTotal.papers[paperKey] = { total, ...calcRes } });
内容的提问来源于stack exchange,提问作者Fathe
相关产品推荐
相关产品推荐

