So the following code should result in the log displaying an array with firstly just the Ticket object with a quantity of 1, then secondly the same Ticket object but with a quantity of 4. Then finally two objects - Ticket with quantity of 3, and a Ticket 2 object with a quantity of 5.
Yet for some reason all three logs are just showing the final result of two objects, despite the functions not being called again until after the initial log. What the hell is happening here?
var basket = [];
var Item = function(name, id, price, quantity){
this.name = name;
this.id = id;
this.price = price;
this.quantity = quantity;
};
function addItemToBasket(name, id, price, quantity){
for (var i in basket){
if (basket[i].id === id){
basket[i].quantity += quantity;
return;
}
}
var item = new Item(name, id, price, quantity);
basket.push(item);
}
function removeItemFromBasket(id){
for (var i in basket){
if (basket[i].id === id){
basket[i].quantity--;
if (basket[i].quantity === 0){
basket.splice(i, 1);
}
return;
}
}
}
addItemToBasket('Ticket', 1, 225, 1);
console.log(basket);
addItemToBasket('Ticket', 1, 225, 3);
console.log(basket);
addItemToBasket('Ticket #2', 2, 450, 5);
removeItemFromBasket(1);
console.log(basket);