Pregunta

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!

¿Fue útil?

Solución

The first time you enter the loop, you set totalPrice to 0. Then you add the first item price, so totalPrice is 25. Then you enter the loop for the second time, set totalPrice to 0 again, 0 + 50 = 50.

You should initialize totalPrice before the loop.

Otros consejos

use reduce:

basket.reduce( function( previousValue, currentValue ){
           return previousValue += parseInt(currentValue.price) 
 }, 0);

example: http://jsfiddle.net/ysJS8/

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top