2017-02-15 67 views
0

我试图用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个不同类别的各种项目。我想知道特定类别的每个项目的小计是什么。

所以想象一下,在一个叫做上衣的类别中,有两件商品都是5美元,而在裤子类别中,我们有3件商品都是12美元。在这种情况下总和需要计算,我有一个总的$ 10上衣类别,共$ 36裤子类

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

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

} 

如何计算在我的动态创建的阵列中的每一个总和?

+1

你可以有第三个数组'subTotals'而不是'totalPrice + = sum [i] [x]'你可以做'subTotals [i] + = sum [i] [x]',然后总计它在一个单独的循环中。通过这种方式,您可以从每个类别获得小计 –

+1

使用不是数组的对象。使用类别名称作为对象的属性名称。提供[mcve]演示 – charlietfl

+0

@HypnicJerk你的意思是这样吗? (var x = 0; x user3478148

回答

2

如何:

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

顺便说一句。你可以使用一个正则表达式去除欧元和空格(也可能是其他的)。

+0

谢谢!您错过了'subTotals [i]'的初始化!我已经用reduce来解决这个问题,但这对我来说仍然是一个很好的答案。也感谢关于使用一个正则表达式的提示。我不知道为什么我没有想到这一点。 – user3478148