计算 Javascript 中具有动态名称的数组之和

Calculate the sum of arrays with a dynamic name in Javascript

我正在尝试计算 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];

}

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

这个怎么样:

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

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