javascript - 在 Javascript 中计算具有动态名称的数组的总和

标签 javascript arrays loops sum parseint

我正在尝试用 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 美元。在这种情况下,总和需要计算出我的上衣类别中总共有$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
});

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

关于javascript - 在 Javascript 中计算具有动态名称的数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254026/

相关文章:

c# - 如何在 c# 中的打包记录中读取固定大小字符串的 Delphi 数组

javascript - 从密码生成器创建密码列表

javascript - react native : Tried to run my first app

javascript - 测试对象数组中的值

javascript - 在 promise 中使用 Async/Awaits

javascript - 按键排序映射返回排序后的 Map 对象,其第一个键位于最后一个索引中

php - 将多个值插入同一列名称+覆盖/更新现有条目?

loops - 普通口齿不清 : Empty variable list for DO

javascript - window.parent.$() 在 IE 中不起作用

javascript - KnockoutJS 通过 ko.utils.extend 继承功能