在javascript中获得总和和平均值 [英] Getting the sum and average in javascript

查看:78
本文介绍了在javascript中获得总和和平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何得到最后一列的总和和平均值。在我的代码中,如果表有一行,两行和三行,它将不会得到正确的值。这只适用于有4行的表。我知道我的错代码,但我无法弄清楚循环如何在.each函数中工作。

How to get the sum and average of the last column.In my code it wont get the correct value if the table has one,two and three rows.This works only on table with 4 rows.I know something wrong with my code but i cant figure it out how the loop works within .each function.

重要说明:这与keyup事件一起运行以更新表数据。它不仅仅是显示。确切地说,它是一种更新形式。

所需输出

Item  | value1 | value 2 | value3 |value 4 | Average 
 01        90      88       87      80        82.25

Total average   82.25     result of 82.25/1 number of row

if two rows

Item  | value1 | value 2 | value3 |value 4 | Average 
 01       90      88       87      80        82.25
 02       80      85       86      84        83.75

    Total average   83     result of (82.25+83.75)/2 number of rows

但是结果出现了多个循环

But the result comes out with multiple loops

Here is the console.log(totalAverage)
86.25
176
264.75
353.5
442.25
86.25
176
264.75
353.5
442.25

问题:如何抑制或跳过这个不必要的值。我只需要86.25来显示总数。注意:这只是现在的单行并且已经遇到了这种错误,如果表有多行那么多少呢?

Problem:How to suppress or skip this unnecessary values.I only need the 86.25 to display in total-ave.Note: this is only single row right now and have already incountered this miscaculation, how much more if the table has multiple rows then?

Html

<tr>
 <th colspan="12"><h4>Card</h4></th>
 </tr>
 <tr>
  <th colspan="3">Subjects</th>
  <th colspan="2">First Grading</th>
 <th colspan="2">Second Grading</th>
  <th colspan="2">Third Grading</th>
  <th colspan="2">Fourth Grading</th>
  <th>Average</th>
  </tr>
   </thead>   
  <tbody>
 @foreach($update_card['AllGrade'] as $subject)
   {!! Form::hidden('grade_id[]',$subject['grade_id']) !!} 
<tr>
 <th colspan="3">{!! $subject->subject !!}</th>
 <td colspan="2">{!! Form::text('term_1[]',$subject->term_1,['class'=>'form-control','name[]'=>'term_1','id[]'=>'term_1','value'=>'0']) !!}</td>
 <td colspan="2">{!! Form::text('term_2[]',$subject->term_2,['class'=>'form-control','name[]'=>'term_2','id[]'=>'term_2','value'=>'0']) !!}</td>
<td colspan="2">{!! Form::text('term_3[]',$subject->term_3,['class'=>'form-control','name[]'=>'term_3','id[]'=>'term_4','value'=>'0']) !!}</td>
 <td colspan="2">{!! Form::text('term_4[]',$subject->term_4,['class'=>'form-control','name[]'=>'term_4','id[]'=>'term_4','value'=>'0']) !!}</td>
 <td colspan="2" class="average" id="average" value="0"> Average</td>
 </tr>
 @endforeach
 <tr>
 <th colspan="11">Total Average:</th>
   <th>{!! Form::text('scholar_GPA',$update_card->scholar_GPA,['class'=>'form-control total-ave','name' => 'total-ave','id' => 'total-ave','value' => '0']) !!}</th>
 </tr>

Javascript代码段

$("input").on("keyup", function(){
 $("tbody tr").each(function() {
    var col=1;
    var tr =1;
    var t = 0;
    var a = 0;

 $(this).children('td').not(':last').each(function () {
 var number = ($(this).children('input').length == 0) ? $(this).html() : $(this).children('input').first().val();
                   // console.log(number);
                   // console.log(col);
                    t += parseInt(number);
                   // console.log(t);

                    a = t/col;
                    col++;

          });
           $(this).children('td').last().html(a);//last td of the  row
          // console.log(a);
           col=1;      
           tr++;


});
    calcTotalave();

    });

        // calculate total average
        function calcTotalave() {
            var totalAve = 0;
            var tot=0;
            var c = 2;
            var count =0;
            $( ".average" ).each(function() {
               // console.log($(this).html());

                var thisAve = parseFloat($(this).html());

                if(!thisAve || thisAve === NaN || thisAve == "") {
                    thisAve = 0;
                }


                totalAve += thisAve;  
                   //alert('count'+thisAve+totalAve); 
                   console.log(totalAve); 

                count++;

            });
                c++;
                totalAve = totalAve/c;
               // console.log(totalAve);

                $("#total-ave").val(totalAve);


        }


推荐答案

更新:在下面添加注释,按空格键运行,基于以下功能。
小提琴是循环遍历并按行计算单元格,因此不需要 .average 类。根据数据库输出,您需要根据html表格布局调整它。

UPDATED: fiddle below with comments, press space-bar to run, based around the below function. the fiddle is made to cycle through and calc cells by row, so no .average class required. You will need to adapt it for your html table layouts as per your database output.

calcTotalave();

});

    // calculate total average
    function calcTotalave() {
        var totalAve = 0;

        $( ".average" ).each(function() {

            var thisAve = parseFloat($(this).text()) || 0; // always return a number

            totalAve += thisAve; 

        });

        var Aver = totalAve / $('.average').length;  
        console.log(totalAve); 

        $("#total-ave").text(Aver);    
    }

而不是将每个单元格分类为 .average 您可以使用选择器定位给定行的所有单元格 td

instead of classing each cell as .average you could use the selector to target all the cells td of a given row:

$('input').change(function() {
    calTotalAverages(); // the magic and collect the total average
});

function calTotalAverages(){
  var SumAve = 0, nums = 0; // to collect total averages and the number of rows
  $('tr').each(function(i) {
    if (i > 0) { // ignore the first row
      var $this = $(this);
      SumAve += calcRowAve($this); // add up the returned averages and run the function
      nums ++; // count the rows
    }
  }); // cycle through each row

  var sum = (SumAve / nums);
  $('#total-ave').text(sum.toFixed(2)); // display the total average
  
  return sum; // return the total average
}

// calculate total average
function calcRowAve(targetRow) {
  var totalAve = 0,
    targetCells = targetRow.children(),
    targLength = targetCells.length - 2; // total number of values in a row

  targetCells.each(function(i) {
    if (i > 0 && i <= targLength) {
      var thisAve = parseFloat($('input',this).val()) || parseFloat($(this).text()) || 0; // always return a number
      totalAve += thisAve;
    } // check to ignore the first cell and the last

  });

  var Aver = totalAve / targLength; // get the average
  targetCells.last().text(Aver); // update the last cell of the row
  return Aver;  // return the average for this row
}

#total-ave {
  position: fixed;
  right: 2em;
  top: 8em;
}

input{
  width: 5em;
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <th>item 1</th>
    <th>value 1</th>
    <th>value 2</th>
    <th>value 3</th>
    <th>value 4</th>
    <th>average</th>
  </tr>
  <tr>
    <td>1</td>
    <td>90</td>
    <td>88</td>
    <td>87</td>
    <td>80</td>
    <td></td>
  </tr>
  <tr>
    <td>2</td>
    <td>80</td>
    <td>85</td>
    <td>86</td>
    <td>84</td>
    <td></td>
  </tr>
  <tr>
    <td>3</td>
    <td><input type='number'></td>
    <td><input type='number'></td>
    <td><input type='number'></td>
    <td><input type='number'></td>
    <td></td>
  </tr>
</table>

<div id='total-ave'></div>

这篇关于在javascript中获得总和和平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆