我正在使用Angular作为我的框架。每当数组发生突变时,我都有一个被调用的函数。我需要在每次调用此函数时检查数组,以查看它是否具有重复项,如果需要,我需要编辑原始项并从数组中删除最后一项。

我正在建立购物车。因此,当将重复项添加到数组中时,我需要更改原始项中的数量值并删除最后推送的项。

组件功能:

ngDoCheck() {
    var changes = this.differ.diff(this.shoppingCart); // check for changes
    if (changes) {
      clearTimeout(this.timer);
      this.cartOpen = true;
      this.itemsInCart = this.numberOfItemsinCart(this.shoppingCart);
      this.cartTotal = this.totalCartAmount(this.shoppingCart);

     //check if this.shoppingCart has a duplicate item
     //if array does have a duplicate
     //change qty value in original item and
     //remove the last item added

   }
 }


我的对象数组示例:

{
    "id": 6,
    "product_name": "name of product",
    "sku": "26-008b",
    "description": "description of product",
    "product_link": "link",
    "cat_id": "categoryId",
    "cat_name": "Category name",
    "related_products": [],
    "sub_cat_name": "sub category name",
    "price": price,
    "qty": 1
}


由于我没有任何想法或凝视此代码太长时间了,将不胜感激。

最佳答案

您可以使用关于数组Array.indexOf(item)Array.prototype.lastIndexOf(item)的javascript内置函数

if(Array.indexOf(item) == Array.prototype.lastIndexOf(item)) {
    // change value in position given by indexOf
    // delete last index
}

10-08 13:11
查看更多