【问题标题】:Calculate the sum of arrays with a dynamic name in Javascript在Javascript中计算具有动态名称的数组的总和
【发布时间】:2017-02-15 15:51:17
【问题描述】:

我正在尝试在 Javascript 中计算具有动态名称的数组的总和。 这是我的代码示例:

            var sum = [];
            var totalPrice = 0;
            //For each unique category
            for (var i = 0; i < uniqueCategoryNames.length; i++) {
                //Create a new array for each unique category
                sum[i] = new Array();

                //Loop through each item with the class name of the unique category
                $('.' + uniqueCategoryNames[i]).each(function () {

                    //Push the trimmed price in the array that matches the category
                    sum[i].push(Number($(this).text().replace('€', '').replace(' ', '').replace(',','.')));
                });

                for (var x = 0; x < sum[i].length; x++){
                    totalPrice += sum[i][x];

                }
                console.log(totalPrice);

            }

描绘一下我的情况:我有一个购物车,里面有 2 个不同类别的各种物品。我想知道特定类别的每个项目的小计是多少。

所以想象一下,我有 2 件商品在名为上衣的类别中均为 5 美元,而在名为裤子的类别中,我有 3 件均为 12 美元的商品。在这种情况下,总和需要计算出我的 tops 类别 中总共有 $10,而我的 中总共有 $36裤子类

我被困在计算所有数组总和的部分。我在这里尝试这样做:

for (var x = 0; x < sum[i].length; x++){
     totalPrice += sum[i][x];

}

如何计算每个动态创建的数组的总和?

【问题讨论】:

  • 你可以有第三个数组subTotals,而不是totalPrice += sum[i][x],你可以做subTotals[i] += sum[i][x],然后在一个单独的循环中把它加起来。这样你就有了每个类别的小计
  • 使用对象而不是数组。使用类别名称作为对象的属性名称。提供minimal reproducible example 演示
  • @HypnicJerk 你是这个意思吗? for (var x = 0; x &lt; sum[i].length; x++){ subTotals[i] = new Array(); subTotals[i] += sum[i][x]; for (var y = 0; y &lt; subTotals.length; y++){ totalPrice = subTotals[i]; } } console.log(totalPrice);
  • 好吧,简单写sum[i]=sum[i].reduce((num,total)=&gt;{return num+total});,这将用所有子数组的总和替换总和数组。不知道你是否想要这个。
  • 您缺少subTotals[i] 的初始化,如subTotals[i] = 0.0; 中一样

标签: javascript arrays loops sum parseint


【解决方案1】:

这个怎么样:

let totalPrice = 0;
let subTotals = {};
//For each unique category
for (let i = 0; i < uniqueCategoryNames.length; i++) {

  let subTotalCurrentCategory = 0;
  //Loop through each item with the class name of the unique category
  $('.' + uniqueCategoryNames[i]).each(function() {

    //Add the current price to the subTotal
    let currentPrice = parseFloat($(this).text().replace(/[€\s]+/g, '').replace(',', '.'));
    if(isNaN(currentPrice) || currentPrice < 0 ) {
      /* can be more checks above, like $(this).text().indexOf('€') == -1 */
      throw new Error("Something wrong on calculating the total");
    }
    subTotalCurrentCategory += currentPrice;
  });

  // Store the current cat subtotal
  subTotals[uniqueCategoryNames[i]] = subTotalCurrentCategory;

  // Add the current subTotal to total
  totalPrice += subTotalCurrentCategory;

}
console.log({
  totalPrice: totalPrice,
  subTotals: subTotal
});

顺便说一句。您可以使用一个正则表达式同时删除 € 和空格(也可能是其他空格)。

【讨论】:

  • 谢谢!我已经使用 reduce 稍微不同地解决了这个问题,但这对我来说仍然是一个很好的答案。还要感谢有关使用一个正则表达式的提示。我不知道为什么我没有想到这一点。
猜你喜欢
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多