Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript count present i value with previous loop output value

function myFunction() {
  var text = "";
  var i;
  for (i = 0; i <= 10; i++) {
    text += + i + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>

<p id="demo"></p>

I want to add present i value into previous loop output value. This maybe a simple question. I have searched in google and stackoverflow. But, didn't get the desired result.

enter image description here

In above screenshot,

0 is the previous loop value + 1 is present i returns => 1
1 is the previous loop value + 2 is present i returns => 3
3 is the previous loop value + 3 is present i returns => 6
6 is the previous loop value + 4 is present i returns => 10

like image 761
Karuppiah RK Avatar asked Jan 27 '23 15:01

Karuppiah RK


2 Answers

You need another persistent variable that keeps track of the last total that was concatenated with text:

function myFunction() {
  var text = "";
  var i;
  var lastTotal = 0;
  for (i = 0; i <= 10; i++) {
    var newTotal = lastTotal + i;
    text += + newTotal + "<br>";
    lastTotal = newTotal;
  }
  document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>

<p id="demo"></p>

(technically, you don't need the newTotal variable, but it makes the code's intent more clear)

You could also do this a bit more elegantly with reduce:

function myFunction() {
  let text = '';
  Array.from({ length: 11 }, (_, i) => i)
    .reduce((lastTotal, i) => {
      const newTotal = lastTotal + i;
      text += newTotal + '<br>';
      return newTotal;
    }, 0);
  document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>

<p id="demo"></p>
like image 132
CertainPerformance Avatar answered Jan 29 '23 06:01

CertainPerformance


You just need a second variable to hold the last value:

function myFunction() {
  var text = "";
  var sum = 0;
  for (var i = 0; i <= 10; i++) {
    sum += i;
    text += sum + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>

<p id="demo"></p>
like image 39
Scott Marcus Avatar answered Jan 29 '23 06:01

Scott Marcus