You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计学生考勤中值为1的记录数并计算出勤率百分比?

考勤统计:出勤数与出勤率计算方案

你已经能计算总考勤记录数,但需要统计出勤(值为1)的记录数并计算出勤率,以下是通用解决方案:

你的考勤数据:

{
  "CGMM": {
    "17:4:2023": 1,
    "19:4:2023": 0
  },
  "CNS": {
    "17:4:2023": 1
  },
  "ML": {
    "17:4:2023": 1,
    "16:4:2023": 1
  }
}

通用解决方案代码

这种方式无需硬编码科目名称,适配科目增减的场景:

const student = { /* 你的考勤数据 */ };

let totalRecords = 0;
let attendedRecords = 0;

// 遍历所有科目数据
for (const subjectAttendance of Object.values(student)) {
  const attendanceValues = Object.values(subjectAttendance);
  // 累加总记录数
  totalRecords += attendanceValues.length;
  // 累加出勤记录数(筛选值为1的记录)
  attendedRecords += attendanceValues.filter(val => val === 1).length;
}

// 计算出勤率,避免除以0错误,保留两位小数
const attendanceRate = totalRecords > 0 ? (attendedRecords / totalRecords * 100).toFixed(2) : 0;

console.log(`总记录数: ${totalRecords}`);
console.log(`出勤记录数: ${attendedRecords}`);
console.log(`出勤率: ${attendanceRate}%`);

代码说明

  • 遍历所有科目:通过Object.values(student)获取所有科目的考勤数据集,无需固定写死科目名
  • 统计总记录数:直接累加每个科目下的考勤记录数量
  • 统计出勤数:用filter筛选出每个科目中值为1的记录,统计其数量后累加
  • 计算出勤率:先判断总记录数不为0(防止除以0报错),再计算百分比并保留两位小数

基于你现有代码的修改方案

如果不想完全重构代码,可在原有基础上添加出勤统计逻辑:

const student = { /* 你的考勤数据 */ };

// 总记录数(添加|| {}避免科目不存在时报错)
const attendenceInML = Object.keys(student.ML || {}).length;
const attendenceInSEA = Object.keys(student.SEA || {}).length;
const attendenceInCGMM = Object.keys(student.CGMM || {}).length;
const attendenceInCNS = Object.keys(student.CNS || {}).length;
const total = attendenceInML + attendenceInSEA + attendenceInCGMM + attendenceInCNS;

// 出勤记录数
const attendedML = Object.values(student.ML || {}).filter(v => v === 1).length;
const attendedSEA = Object.values(student.SEA || {}).filter(v => v === 1).length;
const attendedCGMM = Object.values(student.CGMM || {}).filter(v => v === 1).length;
const attendedCNS = Object.values(student.CNS || {}).filter(v => v === 1).length;
const attendedTotal = attendedML + attendedSEA + attendedCGMM + attendedCNS;

// 出勤率
const attendanceRate = total > 0 ? (attendedTotal / total * 100).toFixed(2) : 0;

内容的提问来源于stack exchange,提问作者Jaydeep Chouhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 10:13:09