我想比较两个对象,看看它们是否相等。对象 A (offer) 是原始对象,对象 B (offerTemp) 是 A 的副本。
对象 A 显示在组件的表中,以查看表中是否有任何更改,我想将 A 与 B 进行比较。但是当我调用函数检查它们是否相等时,它说对象不相等. 我认为这是因为对象 A 具有对象的引用而 B 没有(至少这是我在控制台中记录两个对象时看到的)。
对象 A(报价)(来自控制台):
Offer {id: 1834, title: "A great article offer - 1834", description: "browser", sellDate: Mon Dec 25 2045 21:54:06 GMT+0100 (Central European Standard Time), valueHighestBid: 753, …}
对象 B(offerTemp)(来自控制台):
{id: 1834, title: "A great article offer - 1834", description: "browser", sellDate: Mon Dec 25 2045 21:54:06 GMT+0100 (Central European Standard Time), valueHighestBid: 753, …}
这是来自component.ts
:
ngOnInit(): void {
this.offer = this.offerService.FindById(this.editOfferId);
this.offerTemp = Object.assign({}, this.offer);
}
cancelSelected(offer: Offer): void{
if (offer === this.offerTemp) {
// do stuff...
}
else {
console.log(this.offer === this.offerTemp); // false in the console
console.log(this.offer);
console.log(this.offerTemp);
}
}
这是我的 html 中的一部分:
<div>
<table>
<tr>
<th>Selected offer details: (id: {{offer.id}})</th>
</tr>
<tr>
<td>Title</td>
<td>
<input [(ngModel)]="offer.title" type="text" name="" id="">
</td>
</tr>
<tr>
<td>description</td>
<td>
<input [(ngModel)]="offer.description" type="text" name="" id="">
</td>
</tr>
<tr>
<td>auctionStatus</td>
<td>
<select>
<option *ngFor="let key of keys" [value]="key" [selected]="offer.auctionStatus">{{statusen[key]}}</option>
</select>
</td>
</tr>
<tr>
<td>valueHighestBid</td>
<td>
<input [(ngModel)]="offer.valueHighestBid" type="text" name="" id="">
</td>
</tr>
</table>
<button mat-raised-button (click)="deleteSelected()"> Delete </button>
<button mat-raised-button (click)="saveSelected(offer)"> Save </button>
<button mat-raised-button (click)="clearSelected(offer)" > Clear </button>
<button mat-raised-button (click)="resetSelected(offer)" > Reset </button>
<button mat-raised-button (click)="cancelSelected(offer)"> Cancel </button>
</div>
有没有办法在没有对象引用的情况下比较这些对象或我可以解决这个问题的其他方法?