Javascript-计算Javascript中的HTML表列AVG值不起作用

时间:2018-09-07 13:27:40

标签: javascript laravel average

在Laravel工作。我需要计算“费用”的平均值 但这是行不通的。 这是我的代码:

<table class="table table-striped table-bordered" id="table">
                    <thead>
                      <tr>
                         <th scope="col">ID</th>
                         <th scope="col">Name</th>
                         <th scope="col">Description</th>
                         <th scope="col">Cost</th>

                      </tr>
                    </thead>
                    <tbody id="myTable">
                    @foreach($detailsa as $invoice)
                        @foreach($invoice->subaccountinvoice as $sub_accounts)
                      <tr>
                          <td scope="row">{{$sub_accounts->codeinvoice}}</td>
                          <td scope="row">{{$sub_accounts->userinvoiceperson->user_name}}</td>
                          <td scope="row"><span>{{$sub_accounts->description}}</span></td>
                          <td scope="row"><span>{{$sub_accounts->amount}}</span></td>
                        </tr>
                         @endforeach
                  @endforeach
                  </tbody>
              </table>
    <span id="val"></span>

{{$$ sub_accounts-> amount}}返回一个数字

在javascript中

  <script>
        var table = document.getElementById("myTable"), avgVal, sumVal = 0, 
                    rowCount = table.rows.length - 1;// minus the header

        for(var i = 1; i < table.rows.length; i++)
        {
            sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
        }

        document.getElementById("val").innerHTML = "Average Value = " + parseInt(sumVal / rowCount);
    </script>

最终结果是:NaN,有人可以帮忙吗?谢谢 !

1 个答案:

答案 0 :(得分:1)

似乎您可以将table.rows.length的table.rows.length - 1更改为i = 1的{​​{1}},并添加i = 0,因为您具有span标记。

.children[0]
var table = document.getElementById("myTable"),
  avgVal, sumVal = 0,
  rowCount = table.rows.length;

for (var i = 0; i < table.rows.length; i++) {
  sumVal += parseInt(table.rows[i].cells[3].children[0].innerHTML);
  
}

document.getElementById("val").innerHTML = "Average Value = " + parseInt(sumVal / rowCount);