javascript - 如何保护数组不被刷新
问题描述
我有基于 Clothes 和 Orders 模型的衣服和订单表和数组。每当我将衣服元素推入 Orders 数组时,尤其是更新选择的衣服数量和价格时,衣服数组也会更新,我不想要它。我想让我的数组保持不变。我在互联网上搜索它但没有用。这是我在下面尝试的。另外为了清楚起见,我会在这里添加图片
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
}
}
推荐阅读
- pos - 如何使用 Microsoft POS 打印机画线
- postgresql - Postgres 字符串操作
- movesense - 无法从 AdbBridge 配置 LSM6DS3
- java - 如何将hibernate xml转换为java注解
- c# - 如何在 C# 中的 WPF 应用程序中解锁 Windows 屏幕?
- python - 如何使用枢轴重塑我的熊猫数据框?
- google-cloud-platform - 对 Google 管理的 SSL 证书进行故障排除
- python - 我正在尝试使用 pandas 导入 CSV 文件,但出现错误。(看图片)
- r - 如何根据另一个变量重新排序 X 轴日期
- flutter - 错误:无法在“ServicesBinding?”上访问属性“defaultBinaryMessenger” 因为它可能为空