I am trying to check if an object is within an array, I have managed to do this however I am unable to run the code within the blocks. Here is the code snippet:
basket.add = function(item) {
for(var i = 0; i < this.items.length; i++){
if(item === this.items[i]){
basket.items[i].count += 1;
}else{
basket.items.push(item);
};
};
basket.print();
};
When I run the code without the if statement it works fine apart from the fact it push the obj again. When I check and then push the obj if it is not in the array this code does not work.
Your current code loops through
items
, pushing another reference toitem
to the end of the array each time it finds a value initems
that doesn't matchitem
. I don't think this is what you want.Instead you can use
For users of IE8 and earlier
.indexOf
won't work, so if that's important you can add this polyfill.