For inside For (Explanation)

1

I went back to studying logic, since I was only studying front-end and it struck me a very rough doubt about one from another.

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

As you have seen, it shows me the variable i 10 times, but I just asked (in logic) to show me only the first one that would be (1,2,3,4,5,6,7,8,9 , 10). Because it brought me the values of the other is repeated 10 times. Note: Make a thorough explanation, I could not understand search.

    
asked by anonymous 19.02.2018 / 02:10

2 answers

4

First and foremost I advise you to never use document.write .

About For , it works as a listing, if you make a listing within an item from another list it will end sooner.

Through this example you will see the listing of each item by confirmation making it easy to understand when viewing. I'd recommend testing for 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 parent% child within parent% parent must finish its execution to start the next parent% parent , or one parent will send all the children at a time.

    
19.02.2018 / 02:34
2

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

When running for i the first time:

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

Then it will return for i for the second time (now i is equal to 2 ):

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

And so on until i is equal to 10 .

The first for will wait for processing the second for to continue.

    
19.02.2018 / 02:23