2017-02-15 69 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