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
相关产品推荐
相关产品推荐

