首页 > 解决方案 > 使用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

标签: javascriptjquery

解决方案


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)


推荐阅读