使用 Reduce 方法对 JavaScript 循环中的所有值求和不起作用



我有一个购物车.html页面,用户选择的项目显示在表格中。我想在表格的每一行中显示所有总计的总计。我的代码如下-

function showCart() {
if (cart.length == 0) {
$("#cart").css("visibility", "hidden");
return;
}
$("#cart").css("visibility", "visible");
$("#cartBody").empty();
for (var i in cart) {
var item = cart[i];
var total = item.Qty * item.Price + item.Chrg;
var row = "<tr><td>" + item.Product + "</td><td>" +
item.Price + "</td><td>" + item.Qty + "</td><td>"
+ item.Chrg + "</td><td>"
+ total + "</td><td>"
+ "<button onclick='deleteItem(" + i + ")'>Delete</button></td></tr>";
$("#cartBody").append(row);
}
}

.HTML

<table id="cart" border="1" style="visibility:hidden; width:100%">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Qty</th>
<th>Del. Charge</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody id="cartBody">
</tbody>
</table>

结果 我明白了——

+---------+------+-----+------------+-------+
| Product |Price | Qty | Del.Charge | Total |
+---------+------+-----+------------+-------+
| Chips   | 20   |  5  |  10        | 110   |
| Coke    | 50   |  3  |  10        | 160   |
| Corn    | 10   |  2  |  10        |  30   |
+---------+------+-----+------------+-------+

现在我想在表格底部显示总计,如下所示:

+---------+------+-----+------------+-------+
| Product |Price | Qty | Del.Charge | Total |
+---------+------+-----+------------+-------+
| Chips   | 20   |  5  |  10        | 110   |
| Coke    | 50   |  3  |  10        | 160   |
| Corn    | 10   |  2  |  10        |  30   |
+---------+------+-----+------------+-------+
Grand Total: 200

到目前为止,我试过这个

var gtotal = new Array; //placed above for loop
gtotal = total + ',';
console.log(gtotal); //shows 110,160,30,
var gtotal = [gtotal].reduce((a, b) => a + b, 0);
$("#gtotal").append(gtotal); //append result on div id gtotal on cart.html page

此显示 - 0110,0160,030,//它前缀为 0

gtotal = total + ',';
console.log(gtotal); //shows 110,160,30,
var gtotal = [gtotal].reduce((a, b) => a + b, 0);
$("#gtotal").append(gtotal); //append result on div id gtotal on cart.html page

此显示 - 0110,0160,030,//它前缀为 0

这是因为您在以 0 作为累加器的归约函数中执行a+b。由于您使用[gtotal]作为输入数组,因此只有一个归约步骤:使用110,0160,030,。然后a+b就完成了。将 0 作为累加器时,将0添加到字符串只会导致该行为,因为此处的 + 运算符是串联操作。

我使用.split(',')将数字元素数组中的逗号分隔字符串转换为 String(因此gtotal.split(',')给出了["110", "160", "30", ""])。然后,我使用.map将这些字符串值转换为 Number 类型。最后,.reduce可以用来获得您的总价值。

var gtotal = '110,160,30,';
console.log(gtotal); //shows 110,160,30,
var totalValue = gtotal.split(',').map(s => Number(s)).reduce((a, b) => a + b, 0);
console.log(totalValue);

PS:如果需要,您可以将.map(s => Number(s))缩短为.map(Number)

最新更新