Insert a loop inside another loop

Asked

Viewed 2,606 times

0

I wish to add the second to 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 stays 2 in 1 becoming a compact but functional code.

  • 1

    I do not understand what you are wanting, if you want a tie after another, you are right, you have nothing to invent. If you want something else, it is not clear. You want them both to run the two lines of concurrent code, ie together? Have any difficulty in passing a line from one block into the other?

  • Can you give an example of how it should appear in HTML? It’s not clear to me what you want as a result.

  • 1

    Diego, you saw my question ^ ?

  • @Diego see if there’s anything missing, and leave a comment here, because if you need to understand something I didn’t put in the answer, or more explanations of the examples, I can try to help and clarify better.

1 answer

8



Following version with intercalation, after the question is edited:

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

It’s the same as:

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


If I were to make a matrix:

Two loops inside each other would be more suitable to make a matrix:

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 I 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 one from 0 to 19.

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

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

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


Just to be more didactic, follow a version of the first version simpler to read, but that works 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 if that is "hidden" in the first code, just see this question:

Use of ? and : in PHP

The language is different, but the functioning of the ? : is the same.

Browser other questions tagged

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