Make cumulative value in loop

Asked

Viewed 34 times

1

var previsto = [];
for(var i = 0; i < $(".previsto").length ; i++)
{ 
    previsto[i] =  $(".previsto").eq(i).text();
}

I need to take the next amount adding up the previous one, to have a buildup.

1 answer

1


var previsto = [];
for(var i = 0; i < $(".previsto").length ; i++)
{
    if(i == 0)
      previsto[i] =  $(".previsto").eq(i).text();
    else
      previsto[i] =  previsto[i-1] + $(".previsto").eq(i).text();
}

To sum integers use the parseint function. Full example:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>eq demo</title>
  <style>
  div {
    width: 60px;
    height: 60px;
    margin: 10px;
    float: left;
    border: 2px solid blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div>20</div>
<div>4</div>

<script>
var previsto = [];
for(var i = 0; i < $("div").length ; i++)
{
    if(i == 0)
      previsto[i] =  parseInt($("div").eq(i).text());
    else
      previsto[i] =  parseInt(previsto[i-1]) + parseInt($("div").eq(i).text());

}
console.log(previsto);
</script>
</body>
</html>
  • In this case it groups the values

  • Ex: 20 , 4 Retronara 204. I want it to add the values 20, 4 = 24

  • use the parseint function

  • var predicted = []; for(var i = 0; i < $(". predicted"). length ; i++) { if(i == 0) predicted[i] = parseint($(". predicted"). eq(i). text()); Else predicted[i] = parseint(predicted[i-1]) + parseint($(". forecast"). eq(i). text(); } console.log(provided);

  • Thanks partner, solved my problem!

  • ok. mark the answer as correct :)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.