【问题标题】:How to add values from an array of objects using a for loop?如何使用 for 循环从对象数组中添加值?
【发布时间】:2019-11-29 08:14:25
【问题描述】:

我有一个对象数组(购物车),它的大小可以改变,我需要编写一个函数来添加一个键的所有值(itemPrice)。

我尝试使用 for 循环根据数组长度迭代数组,但我不知道如何将某个键的所有值加在一起。我总是最终只是将第一个值添加到自身中以获得数组的长度。

我的数组看起来像:

[ { itemName: shoes, itemPrice: 12 }, { itemName: socks, itemPrice: 34 }, { itemName: shorts, itemPrice: 56 }

我的 for 循环看起来像:


function total() {
    var total=0;
    for (let i = 0; i <= cart.length; i++) {
        total += cart[i]["itemPrice"] + cart[i]["itemPrice"];
        return total;
    }
}

我希望输出为 102,但总数为 24。我知道为什么是 36,它只是将第一个 itemPrice 添加到自身 3 次,我只是不知道如何让它添加 itemPrice 值彼此。

编辑:是的,我的意思是我得到 24 岁,而不是 36 岁。

【问题讨论】:

  • 你在第一次迭代后返回,我怀疑你得到36你一定得到24
  • 另外,你需要从零循环到length-1
  • 是的,对不起,我已经 24 岁了

标签: javascript arrays for-loop javascript-objects


【解决方案1】:

回答

var cart = [ { itemName: "shoes", itemPrice: 12 }, { itemName: "socks", itemPrice: 34 }, { itemName: "shorts", itemPrice: 56 }];

function total() {
    var total=0;
    for (let i = 0; i < cart.length; i++) {
        total += cart[i]["itemPrice"] ;//+ cart[i]["itemPrice"];
        // return total;// this is wrong it will exit the loop so you need to remove it
    }
    return total;
}
console.log(total());

【讨论】:

  • 是的,就是这样!谢谢,我对编码很陌生,现在我的大脑从学校开始就很煎熬!
  • 欢迎来到世界编码 :) 如果有效,请将其标记为答案
【解决方案2】:

您可以跳过手动循环并改用Array.reduce

const total = cart.reduce((sum, item) => sum + item.itemPrice, 0);

【讨论】:

    【解决方案3】:

    看看这个,例如:

    const cart = [{itemName: shoes, itemPrice: 12 }, { itemName: socks, itemPrice: 34 }, { itemName: shorts, itemPrice: 56 }];
    
    const total = () => {
        const checkProp = cart.prototype.map(e => return e.itemPrice).reduce((a, b) =>{return a + b;
        }, 0);
       return checkProp;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      相关资源
      最近更新 更多