Create and assign variables in For loop

2

How to do 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><pid="G1">10</p>
<p id="G2">20</p>
<p id="G3">30</p>
    
asked by anonymous 16.11.2017 / 17:29

2 answers

1

Whenever you have a variable with a common prefix and then there is a number in a sequence, you should not actually have multiple variables, you should have an array , so the prefix is array and the string 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><pid="G1">10</p>
<p id="G2">20</p>
<p id="G3">30</p>

It has more modern ways of doing this, but not every browser accepts it.

    
16.11.2017 / 17:46
1

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><pid="G1">10</p>
<p id="G2">20</p>
<p id="G3">30</p>
    
16.11.2017 / 17:55