我正在尝试用 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/