Insert a loop into another loop

0

I want to intersperse the second with the first.

For illustration, I will use the simple example below as a basis:

<script>
  n = 10;
  for ( var i = 0; i < n; i++){document.body.innerHTML += i;}

  for ( var i = 0; i < n; i++){c = String.fromCharCode(i+64);document.body.innerHTML += c;}
</script>
  

In short, I want to put the second loop inside the first, so that it gets 2 in 1 making it a compact but functional code.

    
asked by anonymous 09.04.2016 / 05:19

1 answer

8


Followed version with question edit :

for(var i=0; i<10; i++){
   document.body.innerHTML += i + String.fromCharCode(i+64);
}

Gives the same as:

for(var i=0; i<10; i++){
   document.body.innerHTML += i;
   document.body.innerHTML += String.fromCharCode( i + 64 );
}


If you were to make an array :

Two loops within each other would be better suited to make an array:

for(var i=0; i<10; i++){
   for(var j=0; j<10; j++){
      document.body.innerHTML += i + String.fromCharCode( j + 64 ) + ' ';
   }
   document.body.innerHTML += '<br>'; // quebra de linha pra facilitar a leitura
}


If you were to do sequential operations :

for(var i=0;i<20;i++){document.body.innerHTML+=i<10?i:String.fromCharCode(i+54);}

That is, instead of two loops from 0 to 9, we have a 0 to 19.

  • If it is 0 to 9, the% ternary% will add i<10? to the page.

  • else, it will add i . Note that I changed to 54, to discount the difference of the position of the loop. If you do not want String.fromCharCode(i+54) , just use 55;

That is, instead of two loops from 0 to 9, we have a 0 to 19.


Just to stay more didactic, there follows a version of the first simpler version to read, but that works in exactly the same way:

for(var i = 0; i < 20; i++ ) {
  if( i < 10 ) {
    // Aqui faz a parte do 1o loop
    document.body.innerHTML += i; 
  } else {
    // Aqui faz a parte do 2o loop
    document.body.innerHTML += String.fromCharCode( i - 10 + 64 );
  }
}

To understand the @ that is "hidden" in the first code, just see this question:

  

Using? and: in PHP

The language is different, but the operation of if is the same.

    
09.04.2016 / 05:49