简体   繁体   中英

How to sum values using for function in JavaScript?

I need your help. I have created looping function which is FOR to sum the values for specific column.

var result = data.result; //declare result as variable
var rows = result.result.rows; //declare rows as variable
// var sum = 0;
for (var i = 0; rows.length > i; i++) {
  var column = "";
  var total = total_event_loss;
  var sum += parseFloat(rows[i][total_event_loss]);
  column += "<tr><td><center>" + rows[i][category] + "</center></td>";
  column += "<td><center><div class='font-red'>" + sum + "</div>" + rows[i][pic] + "</center></td>";
  column += "<td><center><div class='font-red'>" + rows[i][total_event_loss] + "</div>" + rows[i][field] + "<br/>" + rows[i][sub_category] + "</center></td></tr>";
  $(column).appendTo(container.find("table > tbody"));
}

Initialize the sum variable before the loop, and add to it inside the loop. You can't use the var keyword when adding to it.

var result = data.result;
var rows = result.result.rows;
var sum = 0;
for (var i = 0; rows.length > i; i++) {
  var column = "";
  sum += parseFloat(rows[i][total_event_loss]);
  column += "<tr><td><center>" + rows[i][category] + "</center></td>";
  column += "<td><center><div class='font-red'>" + sum + "</div>" + rows[i][pic] + "</center></td>";
  column += "<td><center><div class='font-red'>" + rows[i][total_event_loss] + "</div>" + rows[i][field] + "<br/>" + rows[i][sub_category] + "</center></td></tr>";
  $(column).appendTo(container.find("table > tbody"));
}

You also never use the total variable, I removed that.

BTW, comments like declare result as a variable are pretty useless. Code comments should clarify things that might not be obvious. It's clear that a var statement declares a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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