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

Ether.js for循环输出优化:如何仅获取最终数组结果

解决Ether.js循环中仅输出最终数组的问题

问题描述

我是一名开发新手,在使用Ether.js编写代码时遇到了for循环相关问题。我的代码如下:

async function claims(epoch) {
  let epochs = [];
  for (let i = 0; i < 10; i++) {
    rounds = epoch - i;
    const claimable = await contract.claimable(rounds, Account);
    const refundable = await contract.refundable(rounds, Account);
    (claimable || refundable) === true ? epochs.push(rounds) : 0
    console.log(epochs);
  }
}
claims()

运行后控制台会输出数组的每一步中间状态:

[100]
[100,99]
[100,99]
[100,99,90]
[100,99,90]
[100,99,90,86]

我希望只拿到循环结束后的最终数组(比如[100,99,90,86]),该怎么改?

修改后的代码

async function claims(epoch) {
  let epochs = [];
  for (let i = 0; i < 10; i++) {
    rounds = epoch - i;
    const claimable = await contract.claimable(rounds, Account);
    const refundable = await contract.refundable(rounds, Account);
    // 优化判断逻辑,直接用布尔值判断,可读性更强
    if (claimable || refundable) {
      epochs.push(rounds);
    }
  }
  // 把打印语句移到循环外面,只输出最终结果
  console.log(epochs);
  // 可以返回数组,方便后续业务调用
  return epochs;
}
claims()

关键修改点

  • 移动打印位置:把console.log(epochs)从for循环内部移到外部,原代码每次循环都会打印数组的当前状态,移到循环结束后就只会输出最终的完整数组。
  • 优化判断逻辑:原三元表达式换成更易读的if语句,且claimable和refundable本身是布尔值,不需要额外和true做严格相等判断。
  • 新增返回值:如果后续需要使用这个数组,可以通过await claims()的方式获取返回的最终数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:13:11