1

我正在尝试遍历数组中的对象,并使用键“价格”添加所有值。

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);
}

我的itemPrice警报显示循环遍历两个对象,闪烁 25 然后 50。为什么我的totalPrice变量只存储第二个价格 50?运算符+=应与totalPrice = totalPrice + itemPrice? 任何解释和修复将不胜感激,试图得到一个很好的理解!

4

2 回答 2

2

第一次进入循环时,设置totalPrice为 0。然后添加第一个项目的价格,因此 totalPrice 为 25。然后第二次进入循环,totalPrice再次设置为 0,0 + 50 = 50。

totalPrice您应该在循环之前进行初始化。

于 2013-01-12T03:30:17.647 回答
0

使用减少:

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

示例:http: //jsfiddle.net/ysJS8/

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

于 2013-01-12T03:53:21.943 回答