[英]How to link shopping cart array with products array?
Here I have array of products which is add products to basket . 在这里,我有一系列产品可以添加产品到篮子里 。 How can I remove certain product from array after I added it to basket by ID ? 在我通过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]);
We will see this in the array of Cart 我们将在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
Firstly, for your Product class you should have another value which reflects a counter for that item. 首先,对于您的Product类,您应该有另一个值,该值反映该项目的计数器。 That way, if someone adds two of the same thing, you just increment that counter rather than adding a whole extra instance of the same object. 这样,如果有人添加了两个相同的东西,你只需增加该计数器而不是添加同一个对象的整个额外实例。
Then, removing things would be easier. 然后,删除东西会更容易。 First you check if the item they want to remove has a counter greater than 1. In that case, just decrement the counter. 首先,检查他们要删除的项目是否有一个大于1的计数器。在这种情况下,只需减少计数器。 Or, if they only have one instance of that item, remove it using filter: 或者,如果他们只有该项的一个实例,请使用过滤器将其删除:
myArray = myArray.filter(function( obj ) {
return obj.id!== 1;
});
This creates a new array btw with a new reference. 这将创建一个带有新引用的新数组btw。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.