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

Firebase数据处理:forEach循环控制台重复输出数组求助

问题解决:Firebase数组提取属性后仅输出最终完整数组

问题描述

从Firebase数据库的对象数组中提取monto_ingreso属性时,使用以下代码:

something.subscribe(res => {
  this.ingresos = res;
  this.ingresos.forEach(ingreso => {
    this.ingresos2.push(ingreso.monto_ingreso);
    console.log(this.ingresos2);
  });
});

Chrome控制台出现阶梯式数组输出:

[20]
(2) [20, 10]
(3) [20, 10, 241]
(4) [20, 10, 241, 10]

但展开每个数组后,都显示完整的4个元素——这是因为Chrome控制台输出的是数组引用,展开时会读取数组当前的实际状态,而非log时刻的快照。现在需要仅输出最终的完整数组。

解决方案

方案1:将console.log移出循环

把打印操作放到forEach循环外部,等所有元素push完成后再打印最终数组:

something.subscribe(res => {
  this.ingresos = res;
  this.ingresos.forEach(ingreso => {
    this.ingresos2.push(ingreso.monto_ingreso);
  });
  console.log(this.ingresos2); // 循环结束后打印完整数组
});

方案2:使用map直接生成目标数组(推荐)

用数组的map方法替代forEach+push,更简洁高效,生成完整数组后直接打印:

something.subscribe(res => {
  this.ingresos = res;
  this.ingresos2 = this.ingresos.map(ingreso => ingreso.monto_ingreso);
  console.log(this.ingresos2); // 打印生成的完整数组
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:36:25