Javascript Looping With Sum Operation

Advertisements

I want to Loop a NAFAG field and sum every NAFAG field with a scheme like this. Every time I repeat the NAFAG sum, the result should be added to the KNAFA field

  • 0 + -30000 results to the 2nd row KNAFA field
  • 0 + -30000 + -30000 results to the 3rd row KNAFA field
  • 0 + -30000 + -30000 + -30000 results to the 4th row KNAFA field
  • 0 + -30000 + -30000 + -30000 + -30000 results to the 5th row KNAFA field

can anyone help me with this loop.

>Solution :

I hope my code help you.

HTML

<table>
  <thead>
    <th>KNAFA</th>
    <th>NAFAG</th>
  </thead>
    <tbody>
    </tbody>
</table>

Javascript

let nafag = [0, -3000, -3000,-3000,-3000,-3000, -3000];
let sum = 0;
for (const elem of nafag) {
    sum += elem;
  let elements = "<tr><td>" + sum + "</td><td>" + elem + "</td></tr>";
  var parent_tbody = document.getElementsByTagName("tbody");
 
  var new_tr = document.createElement('tr');
  new_tr.innerHTML = elements;
  parent_tbody[0].appendChild(new_tr);
}

Result


KNAFA   NAFAG
0       0
-3000   -3000
-6000   -3000
-9000   -3000
-12000  -3000
-15000  -3000
-18000  -3000

Leave a ReplyCancel reply