的項目以前添加到購物車不能正常工作。現在我想更新這個現有項目的值。在addToCart函數中,findItem()函數檢查購物車並返回對現有項目的引用。因爲該項目存在,我只需將從findItem()函數返回的現有項目分配給newItem,如下所示:existingItem = newItem。我希望existingItem這已經是在車到現在的newitem的值,但是當我在車打印項目,existingItem仍然有其先前的值,而不是的newitem值。角2:通過引用傳遞對象的要求
export class CartItem {
product: Product;
quantity: number;
itemTotal: number;
color: string;
protectionPlan: string;
}
export class Cart {
total: number = 0;
numberOfItems: number = 0;
items: CartItem[] = [];
findItem(id: String) : CartItem {
for(let i=0; i < this.items.length; i++) {
if(this.items[i].product._id == id) {
console.log("*************** item found ********************")
return this.items[i];
}
}
return null;
}
addItem(newItem: CartItem) {
let existingItem: CartItem = this.findItem(newItem.product._id);
if(existingItem) {
existingItem = newItem;
//existingItem.quantity = newItem.quantity;
console.log("update item id = " + existingItem.product._id);
console.log("update item quantity = " + existingItem.quantity);
console.log("update item color = " + existingItem.color);
console.log("update item protectionPlan = " +
existingItem.protectionPlan);
} else {
this.items.push(newItem);
this.numberOfItems++;
}
console.log("cart = " + JSON.stringify(this.items));
}
}
程序的當前行爲實際上是所預期的。刪除existingItem = newItem;並且數量屬性至少應該更改 –
existingItem = newItem是如何將新項目的值分配給購物車中已有的項目。如果我刪除它,購物車中的物品不會獲得新的值。 – koque
不是,查看我的答案;) –