【问题标题】:Looping through objects within an array, taking total of integer values遍历数组中的对象,获取整数值
【发布时间】: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


【解决方案1】:

第一次进入循环,你将totalPrice设置为0。然后你添加第一个项目的价格,所以totalPrice是25。然后你第二次进入循环,再次设置totalPrice为0, 0 + 50 = 50。

你应该在循环之前初始化totalPrice

【讨论】:

    【解决方案2】:

    使用减少:

    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

    【讨论】:

      猜你喜欢
      • 2012-09-14
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 2011-06-24
      相关资源
      最近更新 更多