简体   繁体   English

使用reduce方法对javascript循环内的所有值求和不起作用

[英]sum all the values inside javascript loop using reduce method is not working

I have a shopping cart.html page where user selected items displays in a table. 我有一个shopping cart.html页面,其中用户选择的项目显示在表格中。 I want to show Grand Total of all totals in each row of the table. 我想在表格的每一行中显示所有总计的总计。 My code are as follows- 我的代码如下-

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 的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>

RESULT I get this - 结果我得到这个-

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

Now I want to show Grand Total at bottom of the table, like this: 现在,我想在表格底部显示“总计”,如下所示:

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

So far I tried this 到目前为止,我已经尝试过

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

This displays - 0110,0160,030, //it is prefixing 0 显示-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

This displays - 0110,0160,030, //it is prefixing 0 显示-0110,0160,030,//前缀为0

That is because you are doing a+b in your reducing function with 0 as accumulator. 那是因为您正在用0作为累加器在归约函数中执行a+b Since you are using [gtotal] as input array, there is only one reduce step: with 110,0160,030, . 由于将[gtotal]用作输入数组,因此只有一个减少步骤: 110,0160,030, Then a+b is done. 然后完成a+b With your 0 as accumulator, adding 0 to a string just leads to that behavior because the + operator here is a concatenation operation. 使用0作为累加器,将0添加到字符串仅会导致该行为,因为此处的+运算符是串联操作。

I have used .split(',') to turn your comma separate string in an array of numeric elements as String (so gtotal.split(',') gives ["110", "160", "30", ""] ). 我已经使用.split(',')来将数字元素数组中的逗号分隔字符串转换为String(因此gtotal.split(',')给出["110", "160", "30", ""] )。 Then I used .map to convert these string values to a Number type. 然后,我使用.map将这些字符串值转换为Number类型。 At last, .reduce can be used to get your total value. 最后, .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: you can shorten .map(s => Number(s)) into .map(Number) if you want. PS:您可以根据需要将.map(s => Number(s))缩短为.map(Number)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM