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

Ionic/TypeScript中统计数组元素始终返回0的问题排查

Ionic Storage统计非Options开头条目时count始终为0的解决方法

在开发Ionic应用时,使用Storage存储表单条目与选项,尝试统计非Options开头的条目数量,但count变量始终返回0。虽然遍历后trackingEntries能正确存入3个符合条件的元素,但打印count时结果为0。

原代码

async getAllEntries()
{
let count = 0;
this.trackingEntries = [];
this.storage.forEach((value, key, index) => 
{
  if (key != "Options0" && key != "Options1"  && key != "Options2"  && key != "Options3"  )
  {
    this.trackingEntries.push(value);
    count++;
  }
})
console.log(this.trackingEntries);  
console.log("Count: " + count);
}

问题原因

Ionic的Storage.forEach()是异步操作,它返回Promise,但原代码没有等待该操作完成就直接执行了console.log。此时count的自增逻辑还未执行,所以打印的是初始值0。而trackingEntries是引用类型的数组,控制台会实时更新其内容,因此你能看到后续存入的元素,但count作为基本类型,打印的是执行时的快照值。

解决方案

  1. 使用await等待storage.forEach()执行完成,确保统计逻辑全部执行后再输出结果;
  2. 优化key的判断逻辑,用key.startsWith('Options')替代逐个枚举,提升代码简洁性与扩展性。

修改后的代码

async getAllEntries() {
  let count = 0;
  this.trackingEntries = [];
  // 等待异步遍历完成
  await this.storage.forEach((value, key) => {
    // 筛选非Options开头的条目
    if (!key.startsWith('Options')) {
      this.trackingEntries.push(value);
      count++;
    }
  });
  console.log(this.trackingEntries);  
  console.log("Count: " + count); // 此时会正确输出3
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:35:23