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

For循环无法正确存储数据,我的代码哪里存在错误?

问题根源

你将EnrolledNum数组的初始化语句放在了第二个for循环内部,每次循环迭代时都会重新创建一个空数组覆盖之前的EnrolledNum变量,因此每轮只会往新的空数组里存入当前循环的数值,最终循环结束后只剩下最后一轮循环存入的结果。

修正方案

把var EnrolledNum = [];移到第二个for循环的外部即可,修改后代码如下:

fetchInitialData = async () => {
    this.setGlobal({ loading: true });
    const ep = `${process.env.REACT_APP_API}/partners/programs/list`;
    const results = await axios.get(ep);
    console.log("results data", results);

    var param1 = [];
    for (let i = 0; i < results.data.data.length; i++) {
      param1.push(results.data.data[i].id);
    }
    console.log("Param....", param1);

    // 数组初始化移到循环外部
    var EnrolledNum = [];
    for (let j = 0; j < param1.length; j++) {
      console.log('chekcingJ',j,'CheckingParam#', param1[j])

      const customers_ep = `${process.env.REACT_APP_API}/partners/programs/customers/${param1[j]}`;
      const customers = await axios.get(customers_ep);
      console.log("customers....", customers);

      EnrolledNum.push(
        customers.data.data.filter(
          e =>
            e.status_stage === "Accepted_Paid" ||
            e.status_stage === "Accepted_Manual"
        ).length
      );

      console.log("In the Loop: EnrolledNumber...", EnrolledNum);
    }

    console.log("Outside the Loop: EnrolledNumber...", EnrolledNum);
  };

额外提示

日常开发建议优先用const、let声明变量,避免var的变量提升特性带来的作用域混淆问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:45:02