【发布时间】:2013-01-12 03:23:15
【问题描述】:
我正在尝试遍历数组中的对象,将所有值与键“价格”相加。
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 一样吗?任何解释和修复都将非常感谢,试图得到一个很好的理解!
【问题讨论】:
-
因为您在循环中将 totalPrice 设置为 0。你应该在循环之前做。
-
或者你可以使用
Array.reduce():var totalPrice = basket.reduce(function(pr, cur) { return pr + parseFloat(cur.price); }, 0);(演示:jsfiddle.net/XqU5P)
标签: javascript arrays loops for-loop parsefloat