javascript - 使用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
那是因为您正在a+b
使用 0 作为累加器进行归约函数。由于您使用[gtotal]
的是输入数组,因此只有一个 reduce 步骤:with 110,0160,030,
。然后a+b
就完成了。使用 0 作为累加器,添加0
到字符串只会导致这种行为,因为这里的 + 运算符是连接操作。
我曾经.split(',')
将数字元素数组中的逗号分隔字符串转换为字符串(所以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)
推荐阅读
- flutter - 在某些情况下,颤振底部工作表对话框未调整大小
- javascript - 为什么我的 jQuery 代码不能在移动平台上运行?
- python - 使用 matplotlib 更改小提琴图中单个最大和平均线的颜色
- javascript - 无法获取目录中的子文件夹
- redis - 如何提高redis hyperloglog的准确性
- r - B * (sd.x/sd.y) 中的警告:较长的对象长度不是较短对象长度的倍数,对于 r^2 值使用 psem 和 NA
- python - 比较两个具有不同长度的数据框以查找特定列中的差异
- python - Django - 序列化 ManyToMany 属性的主键列表?
- android - ANRWatchDog 库发生了 ANRError 但我不明白为什么会发生
- python-3.x - 在 PyAutoGUI 中使用 region 关键字参数抛出“TypeError: cannot unpack non-iterable NoneType object”