Create and assign loop variables For

Asked

Viewed 1,419 times

3

How to make this logic within a loop FOR ?

var G1 = $('#G1').text()
var G2 = $('#G2').text()
var G3 = $('#G3').text()

console.log("NaN")
console.log(G1+"\n"+G2+"\n"+G3)
console.log(G1+G2+G3)

G1 = parseFloat(G1)
G2 = parseFloat(G2)
G3 = parseFloat(G3)

console.log("Agora Números")
console.log(G1+"\n"+G2+"\n"+G3)
console.log(G1+G2+G3)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p id="G1">10</p>
<p id="G2">20</p>
<p id="G3">30</p>

  • Where will you use the values of G1, G2, etc...? these elements have a common parent element?

  • What do you want to do more specifically? Not clear enough

  • You’re wanting to take the "id" text and do what exactly inside the for??

  • It’s simply taking the variables of p and add. Maniero answered exactly what I needed. Thank you :)

2 answers

2


Whenever you have a variable with a common prefix and then you have a number forming a sequence, actually you shouldn’t have multiple variables, you should have a array, so the prefix is the name of the array and the sequence is the index of array, this way you can create a loop and use its variable as the index of this array.

var G = [];
for (var i = 0; i < 3; i++) {
    G[i] = $('#G' + (i + 1)).text();
}
console.log("NaN");
var soma = 0;
for (var i = 0; i < 3; i++) {
    console.log(G[i] + "\n");
    soma += G[i];
}
console.log(soma)
for (var i = 0; i < 3; i++) {
    G[i] = parseFloat(G[i]);
}
console.log("Agora Números")
var soma = 0;
for (var i = 0; i < 3; i++) {
    console.log(G[i] + "\n");
    soma += G[i];
}
console.log(soma)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="G1">10</p>
<p id="G2">20</p>
<p id="G3">30</p>

I put in the Github for future reference.

There are more modern ways to do this, but not every browser accepts.

  • Perfect! Thank you!!

2

var elems = Array.prototype.slice.call(document.getElementsByTagName('p'));

console.log(NaN);
elems.forEach(function(elem){
  console.log(elem.innerText);
});

console.log("Agora Números")
let aux = 0;
elems.forEach(function(elem){
  var i = parseFloat(elem.innerText);
  console.log(i);
  aux += i;
});

console.log(aux);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p id="G1">10</p>
<p id="G2">20</p>
<p id="G3">30</p>

Browser other questions tagged

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