簡體   English   中英

遍歷數組但總是返回最后一個值

[英]Iterating thorugh array but always returning last value

我正在遍歷一個數組並嘗試為數組中的每個對象獲取不同的數據,但我最終得到相同的數據,如果我在 billBodies 中有三個產品,我最終得到三個具有相同值的項目(例如我有 3 個糖果, 2 杯咖啡和 4 塊糖果我得到的結果是 4 塊糖果、4 塊糖果、4 塊糖果)。 希望任何人都可以幫助我嘗試搜索類似的問題,但沒有找到它......

 for (let bill of dataOfBillHeader.billBodies) {
        console.log(dataOfBillHeader)
        console.log(this.productToShowOnView)
      
        
        this.productToShowOnView.cipher = bill.product.cipher;
        this.productToShowOnView.name = bill.product.name;
        this.productToShowOnView.measure = bill.product.measure;
        this.productToShowOnView.count = bill.product.count;
        this.productToShowOnView.price = bill.product.price;
        this.productToShowOnView.id = dataOfBillHeader.id;
        this.productToShowOnView.count = bill.count;
        this.productToShowOnView.quantity = bill.quantity;
        this.productToShowOnView.discount = bill.discount;
        this.productToShowOnView.discountAmount = bill.discountAmount;
        this.productToShowOnView.totalPrice = bill.totalPrice;
        console.log("to show on view is " + JSON.stringify(this.productToShowOnView));
        
        const newBasket = this.productsInBasket;
        this.productsInBasket.push(this.productToShowOnView);
        this.productsInBasket = [...newBasket];
        this.cd.detectChanges();
      }

好吧,您只是一遍又一遍地推送同一個對象(引用),即this.productToShowOnView 你為什么使用this.productToShowOnView 為什么不是局部常數。 用一點魔法你可以讓它更小一點,雖然我不明白為什么你會從一種產品數據格式轉到另一種......:

const newBasket = [...this.productsInBasket];

for (let bill of dataOfBillHeader.billBodies) {
  const product = { 
    // no need to get all those individually
    ...bill.product,
    ...bill,
    //this is weird, all products have the same id?
    id: dataOfBillHeader.id,
  };

  newBasket.push(product);
}

this.productsInBasket = newBasket;
this.cd.detectChanges();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM