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

如何清除Angular工时表模块提交时残留的旧数据?

问题根因

你的代码存在两个导致旧值残留的问题:

  1. monObj/tueObj/wedObj/thursObj/friObj未在循环内部声明,作用域属于外层函数,且每次循环都没有重置初始值。当某一天的表单输入为空时,对应if分支不执行,变量会保留上一次循环/上一次提交时的旧值。
  2. 不管五个日期对象是否有有效值,都统一全部推入dayArr,导致旧值被带到最终payload中。
修复方案

核心调整点

  • 每次循环开始时先重置所有日期对象的初始值为null,清除上一轮残留值
  • 仅将本次循环中确实赋值的有效对象推入dayArr,如果业务要求空值也要传0小时,则统一给空的位置生成值为0的对象即可
  • 把原有var替换为let,使用块级作用域避免变量提升导致的作用域混乱

修复后代码示例

for (let i=0; i<counter; i++){
  let dayArr = [];
  // 每次循环先重置所有日期对象,清除上一轮残留值
  let monObj = null, tueObj = null, wedObj = null, thursObj = null, friObj = null;

  if (this.tform.value.timesheet[i].mon != null && this.tform.value.timesheet[i].mon != ''){
    monObj = {
      workdate: arr[0].date, 
      hoursspent: Number(this.tform.value.timesheet[i].mon)
    }
  }
  if (this.tform.value.timesheet[i].tue != null && this.tform.value.timesheet[i].tue != ''){
    tueObj = {
      workdate: arr[1].date,
      hoursspent: Number(this.tform.value.timesheet[i].tue)
    }
  }
  if (this.tform.value.timesheet[i].wed != null && this.tform.value.timesheet[i].wed != ''){
    wedObj = {
      workdate: arr[2].date,
      hoursspent: Number(this.tform.value.timesheet[i].wed)
    }
  }
  if (this.tform.value.timesheet[i].thur != null && this.tform.value.timesheet[i].thur != ''){
    thursObj = {
      workdate: arr[3].date,
      hoursspent: Number(this.tform.value.timesheet[i].thur)
    }
  }
  if (this.tform.value.timesheet[i].fri != null && this.tform.value.timesheet[i].fri != ''){
    friObj = {
      workdate: arr[4].date,
      hoursspent: Number(this.tform.value.timesheet[i].fri)
    }
  }
  // 仅把非空的有效对象推入数组
  [monObj, tueObj, wedObj, thursObj, friObj].forEach(item => {
    if (item) dayArr.push(item);
  });
  // 【可选:如果业务要求空值也要传0小时,替换上面的forEach逻辑为以下代码】
  // dayArr = [
  //   monObj ?? {workdate: arr[0].date, hoursspent: 0},
  //   tueObj ?? {workdate: arr[1].date, hoursspent: 0},
  //   wedObj ?? {workdate: arr[2].date, hoursspent: 0},
  //   thursObj ?? {workdate: arr[3].date, hoursspent: 0},
  //   friObj ?? {workdate: arr[4].date, hoursspent: 0},
  // ]
  let tmpPayloadObj = {
    timesheetId: this.tform.value.timesheet[i].timesheetId??0,
    projectid: this.tform.value.timesheet[i].project,
    taskid: this.tform.value.timesheet[i].task,
    dayListDetail: dayArr,
    totalHours: 0
  }
  finalArr.push(tmpPayloadObj)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:15:04