I am trying to loop through objects within an array, adding all values with the key ‘price’.
var basket = [
{
price: "25.00",
id: "Hat"
}, {
price: "50.00",
id: "Jacket"
}
]
/*objects within array. purpose = able to use a for loop using .length as follows*/
function test() {
for(var i = 0; i < basket.length; i++){
totalPrice = 0;
alert(itemPrice);
itemNum = basket[i];
itemPrice = parseFloat(itemNum.price);
totalPrice += itemPrice;
}
alert(totalPrice);
}
My itemPrice alert shows that the loop runs through both objects, flashing 25 then 50. Why is my totalPrice variable only storing the second price, 50? The operator += should be the same as totalPrice = totalPrice + itemPrice? Any explanation as well as fixes would be very much appreciated, trying to get a good understanding!
The first time you enter the loop, you set
totalPriceto 0. Then you add the first item price, so totalPrice is 25. Then you enter the loop for the second time, settotalPriceto 0 again, 0 + 50 = 50.You should initialize
totalPricebefore the loop.