如何将购物车阵列与产品阵列相关联?

时间:2016-10-29 22:05:59

标签: javascript arrays oop inheritance

这里我有产品阵列将产品添加到购物篮。 在我通过 ID 将其添加到购物篮后,如何从数组中删除某些产品

  //Product class
    function Product(options) {
      this.id = options.id;
      this.name = options.name;
      this.cost = options.cost;
      this.quantity = options.quantity;
      this.shortDescription = options.shortDescription;
      this.fullDescription = options.fullDescription;
    }

//Basket class
function Cart() {
  this.items = [];
}

//Add product in basket
Cart.prototype.addItem = function(options) {
  //If we find the same element in array by name, just +1 to quantity in basket
  options.quantity = 1;
  for (var i in this.items) {
    if (this.items[i].id === options.id) {
      this.items[i].quantity += options.quantity;
      return;
    }
  }
  var item = new Product(options);
  this.items.push(item);
};


var arrayOfProducts = [
  {id:1, name:'book', cost:5.45, quantity:5, shortDescription: 'Short description about book', fullDescription: 'Full description about book'},
  {id:2, name:'pan', cost:7.31, quantity:2, shortDescription: 'Short description about pan', fullDescription: 'Full description about pan'},
  {id:3, name:'cup', cost:9.37, quantity:4, shortDescription: 'Short description about cup', fullDescription: 'Full description about cup'},
]

cart.addItem(arrayOfProducts [0]);
cart.addItem(arrayOfProducts [0]);
cart.addItem(arrayOfProducts [1]);

我们将在Cart

数组中看到这一点
id:1, name:book, cost:5.45, quantity:2, short description: Short description about book, full description: Full description about book
,id:2, name:pan, cost:7.31, quantity:1, short description: Short description about pan, full description: Full description about pan

2 个答案:

答案 0 :(得分:0)

首先,对于您的Product类,您应该有另一个值,该值反映该项目的计数器。这样,如果有人添加了两个相同的东西,你只需增加该计数器,而不是添加同一个对象的整个额外实例。

然后,移除东西会更容易。首先,检查他们要删除的项目是否有一个大于1的计数器。在这种情况下,只需减少计数器。或者,如果他们只有该项目的一个实例,请使用过滤器删除它:

myArray = myArray.filter(function( obj ) {
    return obj.id!== 1;
});

这会创建一个带有新引用的新数组btw。

答案 1 :(得分:0)

以上代码缺少购物车的声明。

var cart = new Cart();