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

Angular日志异常问题:数组未执行push却显示更新后内容

问题:Angular中console.log数组先执行却显示push后的结果

调用addProduct方法时,明明先执行console.log(this.orderItems)打印数组,再执行push添加新元素,但控制台展开日志后,显示的却是添加元素后的数组内容。该数组通过*ngFor在HTML中渲染。

相关代码

component.ts文件

interface OrderItem {
  quantity: number | null,
  product: any
}

export class Component{

orderItems: OrderItem[] = [{ quantity: null, product: {} }]

addProduct(): void {
    console.log(this.orderItems);
    this.orderItems.push({ quantity: null, product: {} })
  }

}

HTML文件

<mat-form-field>
        <ng-container *ngFor="let ele of orderItems">
          <mat-form-field>
            <mat-label>Product</mat-label>
            <mat-select [(ngModel)]="ele.product">
                <mat-option *ngFor="let e of productlist" [value]="e._id" >{{e.productName}}</mat-option>
            </mat-select>
          </mat-form-field>
        
        <mat-form-field>
          <mat-label>Number of Items</mat-label>
          <input matInput type="number" [(ngModel)]="ele.quantity" placeholder="Enter the number of items">
        </mat-form-field>
        <br>
        </ng-container>
      <button mat-icon-button (click)="addProduct()">
        <mat-icon>add</mat-icon>
      </button>

</mat-form-field>

异常现象

控制台初始显示[{…}],点击展开后,显示的是包含两个对象的数组:

[{ quantity: null, product: {} },{ quantity: null, product: {} }]

原因及解决方法

  • 原因:这不是Angular的问题,是浏览器控制台的特性——打印引用类型(数组、对象这类)时,采用惰性求值。打印瞬间只是记录了数组的内存引用,当你点击展开查看时,才会去读取数组的当前状态,这时候push已经执行完成,所以看到的是修改后的结果。
  • 解决方法:
    • 打印数组的快照:用console.log(JSON.parse(JSON.stringify(this.orderItems))),通过JSON序列化再反序列化,生成当前数组的深拷贝副本,这样打印的就是执行console.log时刻的数组状态。
    • 浅拷贝数组:如果数组元素是简单类型或不需要深拷贝,直接用console.log([...this.orderItems])创建新数组副本打印。
    • 断点调试:在console.log之后加断点,阻止代码继续执行,就能看到打印时的真实数组状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:00:34