Inside For (Explanation)

Asked

Viewed 923 times

1

I returned to study logic, because I was studying only front-end and hit me a very rough doubt, about one was of another.

for (var i = 1; i <=10  ; i++) {
				for (var i2 = 1; i2 <=10; i2++){
				document.write(i);
				
			}
			}

As you have seen he shows me the variable i 10 times, but I only asked (in logic) that he show me only first if it would be (1,2,3,4,5,6,7,8,9,10). Because he brought me the other’s values be repeated 10 times. Note: Make an explanation in depth, I could not understand by researches.

  • 1

    As you placed one for inside the other, the first for goes from 1 to 10 and the second for 1 to 10 and you are asking to print the value of the variable of the first for inside the second for, this will cause the i value to repeat 10 times in the first interaction and so repeat successively until finished. In case will print 10 times the 1, 10 times the 2 ..... up to 10 times the 10.

2 answers

4

First of all I advise never user document.write.

About For, it works as a listing, if you make a listing inside an item from another list this will end before.

Through this example you will see the listing of each item by confirmation making it easy to understand when viewing. I advise testing by Firefox:

function listar(){
  var lista = document.getElementById("listagem");
  lista.innerHTML = ""; //Limpar listagem para reiniciar
  for(i=1;i<=3;i++){
    lista.innerHTML += "LISTA PAI:" +i + "\n";
    for(j=1;j<=3;j++){
      lista.innerHTML += "\tLista Filho: " +j + "\n";
        alert("Pai "+i+" - Filho: "+j);
    }
  }
}
<input type="button" onclick="listar()" value="LISTAR" />
<pre id="listagem">
</pre>

The for son within the for father has to finish its execution to start the next for father, that is, a father will send all the children at a time.

  • Very good! + 1 !

  • A question: pq vc advises to test by Firefox?

  • Or IE11, Chrome or Opera shows no changes to the page until all ALERT stop.

  • I’m more of a debug fan. So I don’t like how you display the iteration. But the explanatory part seems very good to me at first glance

  • If you were a beginner you might not even know what you are debug or how to really use, I’m sure?

2

On entering the second for, it will repeat 10 times the i of the first for and so on:

When executing the for i the first time:

irá repetir 10x o valor de `i` no segundo `for` (i2 <=10)

You will then return to for i for the second time (now the i is equal to 2):

irá repetir 10x o valor de `i` no segundo `for` novamente

And so on and on until i be equal to 10.

The first for will await processing of the second for to continue.

Browser other questions tagged

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