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

如何遍历对象数组?循环失效与索引值访问问题求助

问题根源

核心问题是异步代码执行时序错误:

  • this.employeeService.getAllEmployees() 是异步操作(返回Promise),你调用它后立刻执行console.log(employeeList)和for循环,但此时then回调还没触发,employeeList还是初始空数组,所以循环根本不会执行。
  • 你的方法声明返回Observable<WorkingHours[]>,但当前代码没有正确返回结果,调用方最终拿不到工时数据。
修复方案

方案1:用async/await + RxJS转换结果

把方法改成异步函数,等待员工列表加载完成后再批量请求工时,最后把结果包装成Observable返回:

import { from, Observable } from 'rxjs';

public async selectWorkingHourListForCurrentMonthAndEveryEmployee(month: Date): Observable<WorkingHours[]> {
  const firstDay = new Date(month);
  firstDay.setDate(1);
  const lastDay = new Date(
    firstDay.getFullYear(),
    firstDay.getMonth() + 1,
    0
  );

  // 等待员工列表加载完成
  const employeeList: Employee[] = await this.employeeService.getAllEmployees();
  
  // 给每个员工发起工时请求,收集所有Promise
  const workingHoursRequests = employeeList.map(employee => 
    this.workingHoursService.getWorkingHours(
      employee.employeeId,
      firstDay,
      lastDay,
      true
    )
  );
  
  // 等待所有请求完成,合并二维数组为一维
  const allWorkingHours = await Promise.all(workingHoursRequests);
  const workingHoursSummedUp = allWorkingHours.flat();

  // 把结果转为Observable返回
  return from([workingHoursSummedUp]);
}

方案2:纯RxJS风格实现

如果项目更偏向RxJS数据流,可以把Promise转成Observable,用操作符链式处理:

import { from, Observable } from 'rxjs';
import { mergeMap, toArray } from 'rxjs/operators';

public selectWorkingHourListForCurrentMonthAndEveryEmployee(month: Date): Observable<WorkingHours[]> {
  const firstDay = new Date(month);
  firstDay.setDate(1);
  const lastDay = new Date(
    firstDay.getFullYear(),
    firstDay.getMonth() + 1,
    0
  );

  return from(this.employeeService.getAllEmployees()).pipe(
    // 遍历员工列表,逐个发起工时请求
    mergeMap(employeeList => 
      from(employeeList).pipe(
        mergeMap(employee => 
          this.workingHoursService.getWorkingHours(
            employee.employeeId,
            firstDay,
            lastDay,
            true
          )
        ),
        // 收集所有结果为数组
        toArray()
      )
    )
  );
}
对象数组遍历补充

如果之后需要遍历填充好的对象数组,推荐这几种方式:

  • for循环:你原来的写法本身没问题,但要确保数组已经被异步操作填充完毕
  • forEach:
    employeeList.forEach(employee => {
      console.log(employee.employeeId);
    });
    
  • for...of(支持异步场景):
    for (const employee of employeeList) {
      console.log(employee.employeeId);
    }
    
  • 不要用for...in遍历数组:它是用来遍历对象键名的,数组用它会拿到索引字符串,还可能遍历到原型链上的无关属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:48:22