我有基于“衣服和订单”模型的衣服和订单表和数组。每当我将衣服元素推入“订单”数组,尤其是更新所选衣服的数量和价格时,衣服数组也要更新,我也不想我想让我的数组保持不变。我在互联网上搜索了它但没有用。这是我在下面尝试的方法。为了清楚起见,我将在此处添加图片

https://imge.to/i/vg2aYm

https://imge.to/i/vg2uvF

的HTML

    <table class="table table-sm">
        <thead>
          <tr>
            <th scope="col">Clothes</th>
            <th scope="col">Price</th>
            <th scope="col"></th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let i of clothesList;let a = index">
            <td>{{i.name}}</td>
            <td>{{i.price}}$</td>
            <td><button class="btn btn-alert" (click)="onAddItem(i)" >Add To Cart</button></td>
          </tr>
        </tbody>
      </table>

   <table class="table" *ngIf="orders.length>0">
                    <thead>
                      <tr>
                        <th scope="col">Clothes</th>
                        <th scope="col">Amount</th>
                        <th scope="col">Price</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr *ngFor="let order of orders;">
                        <td>{{order.name}}</td>
                        <td>{{order.amount}}</td>
                        <td>{{order.price}}</td>
                      </tr>
                    </tbody>
                    <hr>
                    <strong>Total Cost: {{totalCost}}</strong>
                  </table>


TS

export class AppComponent  {
 private clothesList:Clothes[]=[
   new Clothes(1,'Hat',500,1),
   new Clothes(2,'Shoes',150,1),
   new Clothes(3,'Pants',100,1),
   new Clothes(4,'Jacket',200,1),
   new Clothes(5,'T-Shirt',120,1),
   new Clothes(6,'Souvether',150,1),
   new Clothes(7,'Scarf',400,1)
 ];
    private orders:Order[]=[];

    onAddItem(value)
  {
   if(this.orders.find(i => i.name===value.name))
   {
      let myIndex= this.orders.indexOf(value);
      value.amount++;
      this.orders[myIndex].price+=this.orders[myIndex].price;
   }
  else
   {
    this.orders.push(value);
   }
  }
}

最佳答案

这是因为衣服和订单数组中的元素共享相同的引用,因此您需要深度克隆对象以破坏引用:
请尝试以下操作:

onAddItem(value){
        let order = this.orders.find(i => i.name === value.name);
        if (order) {
            value.amount++;
            order.price *= 2;
        }
        else {
            this.orders.push(JSON.parse(JSON.stringify(value))); // break the reference
        }
    }

10-07 14:50