I can not learn syntax for

3

I can learn subjectively for a few seconds, but I can not fix it no matter how hard I try. I've done classes, I've done exercises and everything, but the syntax and variations just do not fix it for me.

For example, if I do:

for(var i=0; i<10; i++){ 
    alert(i); 
}

Calling alert within loop alerts 9 windows at a time by adding 1 number up to 10, normal. But I do not understand why calling alert(i) out of loop only 10 appears.

    
asked by anonymous 24.09.2014 / 05:02

8 answers

18

For syntax:

for(
   INICIALIZACAO;
   CONDICAO para executar o CODIGO entre { };
   tarefa para fazer depois de cada execucao do CODIGO
)
{
   CODIGO a ser executado repetidas vezes, enquanto a CONDICAO for verdadeira
}

I'll show you a step-by-step description. For this, I numbered the lines and decreased to 3 loops only:

1. for( var i=0; i<3; i++ )
2. {
3.    alert(i);
4. }
5. alert(i);

Ok, see how this code is understood by your system:

a) Estamos na linha 1. Aqui foi "criado" um for, e definido que i é zero;  
b) o programa avança para a linha 2, com i valendo zero;
c) avançamos para a linha 3 e é exibido o valor de i, que é zero;  
d) o programa avança para a linha 4. Como o escopo do for encerrou, é executado i++ e testado se i<3
e) i agora é um, portanto SIM, i é menor que três, então VOLTAMOS para a linha 2
f) avançamos para a linha 3, e é exibido o valor de i, que é um;
g) o programa avança para a linha 4. Como o escopo do for encerrou, é executado i++ e testado se i<3
h) i agora é dois, portanto SIM, i é menor que três, então VOLTAMOS para a linha 2
i) avançamos para a linha 3, e é exibido o valor de i, que é dois;
j) o programa avança para a linha 4. Como o escopo do for encerrou, é executado i++ e testado se i<3
k) i é três, portanto NÃO É menor que três, portanto AVANÇAMOS para a linha 5.  
l) Pronto, acabou o loop, i vale 3
m) na linha 5, é exibido o valor de i, que é 3

Note that I have simplified the logic absurdly, the steps are a little more complex internally. As mentioned by @mgibsonbr, the 3 test already happens between steps (a) and (b) , jumping face to line 5 if the result is not true (but not worry about it now).

It is best to understand that this "back and forth" from line 2 through 4 only happens as long as the condition (i

24.09.2014 / 05:37
9

The variable is not scoped (it is not "deleted") as soon as for is over, then i gets the last value of it.

The last comparison in your example and with i = 10 . It does 10 < 10 , which returns false, and exits the loop. Soon, it will print 10 out of the loop.

    
24.09.2014 / 05:07
9

If you're learning loops for the first time, it helps to start with a simpler one - like while - and then move on to for . This will help you understand exactly what happens in your code.

for ( var i = 0 ; i < 10 ; i++ ) { alert(i); }

It is equivalent to:

// Iniciação
var i = 0;
// Teste da condição
while ( i < 10 ) {
    // Corpo
    alert(i);
    // Passo
    i++;
}

Looking at this way, you realize that:

  • The variable was created and assigned to zero even before the loop, and [in JavaScript] it still exists after the loop ends;

        ...
    }
    alert(i); // A variável ainda existe aqui
    
  • There is a chance that he will not enter the loop once!

    var i = 20;
    while ( i < 10 ) {
        ...
    
  • The step is executed before testing the condition; so any side effect it has (in this case, incrementing i ) will occur no matter if the loop will continue or will stop:

        ...
        alert(i); // 9
        i++; // aumentou 1, pra 10
    } // Saiu do loop - pois a condição i < 10 ficou falsa
    alert(i); // 10
    

I suggest you try to dominate while first, because everything else that ties while also does to make - in a simpler but not so concise way. Once you're well-acquainted with it, you can begin to see patterns in its use, and use other ways to simplify those patterns:

  • A code runs once before the loop, and is equal to what is in the body of the loop:

    código
    while ( condição ) {
        código
    }
    

    Can be simplified to:

    do {
        código
    } while(condição);
    
  • One code runs before the loop, and another one at the end of the repeating phase:

    início
    while ( condição ) {
        código
        fim
    }
    

    Can be simplified to:

    for ( início ; condição ; fim ) {
        código
    }
    

    The executed sequence then looks like this:

    • Zero iterations:

      início, condição
      
    • One iteration:

      início, condição, código, fim, condição
      
    • Two iterations:

      início, condição, código, fim, condição, código, fim, condição
      
    • Three iterations:

      início, condição, código, fim, condição, código, fim, condição, código, fim, condição
      
    • Etc.

24.09.2014 / 05:40
3

Well, first of all you need to know when it will be for FOR.

Basically, FOR is for you to repeat an algorithm N times.

Syntax:

for(INICIO DAS VARIAVEIS; CONDIÇÃO ; CONSEQUENCIA ){
  //SEU CODIGO AQUI
}

Example:

var cont;
var totalVoltas = 10;
  for(cont = 0;cont < totalVoltas ;cont++){
    alert("Volta número "+cont);
  }

This code will % with% of the screen, just as you did in the question. In this code, I 10 with INICIALIZEI A VARIÁVEL , soon after I make valor 0 , and at the end CONDIÇÃO plus 1 in the variable that I initialized at the beginning of FOR.

FOR is very used to traversing Array because it has access to all indexes doing this loop. Example:

var semanas = ["Domingo","Segunda","Terça","Quarta","Quinta","Sexta","Sábado"];
var cont;
var str = "Dias da Semana:\n";
//Como um array sempre começa na posição zero, o cont será zero.
for(cont = 0; cont < semanas.length;cont++){
  str += semanas[cont]+"\n";  //Aqui eu 'Acesso' o valor do array contido na posição referente ao valor de cont.
}
alert(str);

The reason why after the loop the value of INCREMENTO is i is that the 10 method changes the variable itself. Thus, at the end of the loop, the count was INCREMENTO times, reaching the end with incrementado 10 .

Beauty, I hope I have helped. :)

    
24.09.2014 / 13:18
2

Different repeat structures: Enquanto(while) , Para(for) , Repita(do)

All three function for the same purpose, they execute a line of code until the pre-established condition is reached .... While and Do does not have in its own basic structure a counter, thus we should create one inside it

  

WHILE

Enquanto (condição) Faça
    (bloco de código)
Fim Enquanto
  

DO

Repita
    (bloco de código)
Ate (condição)

In both above there is a need to declare a counter, and increment it within the block of codes, else the code is in For infinite, and in most cases, especially in high level languages, we do not want that this occurs rs

  

FOR

Para (V) De (vi) Até (vf) Passo (p) Faça
    (bloco de código)
Fim Para

In this case there is no need to declare the counter and increment it within the code block, since we already did it in the pre-established condition ....

The three implementations serve the same purpose, it goes beyond your ease of working with them .....

It would be something like the loop so acclaimed in some "archaic" In the same way we could create a simple structure of GOTO using if

EXP:

linha de memoria 1: I = 0;
linha de memoria 2: Se (I<=5){
linha de memoria 3:    I += 1;
linha de memoria 4:    (bloco de código)
linha de memoria 5:    GOTO linha de memoria 2;
linha de memoria 6: Fim-Se

So it's complicated to explain, we should just add that it serves as a simpler code repeater to be written, so hj is so used, the counter you already define and increments in the condition itself

    
24.09.2014 / 14:51
1

You have to understand to memorize !! It's like a spin, a repetition,

For i starting with 0 up to 10 adding ++ means one step at a time,

  alert ( 1 );

Return

For i starting with 1 to 10 adding ++ means one step at a time,

  alert ( 2 );

Return

And so up to 10

for( var i=0; i<10; i++ )
{ 
 alert(i); 
}
    
24.09.2014 / 13:43
-1

Well, the first step is to learn what is scope, which according to Mauricio Samy Silva (the renowned Maujor) in JavaScript Programmer's Guide:

  

A very important concept when declaring a variable is the so-called variable scope, which is the environment or, more precisely, the part or region of the script in which the variable assumes the value that was declared for it. / em>

Global scope variables can be called anywhere in the script, since local scope variables can be called only in the excerpt of the script in which they were declared. In order to declare a variable in the local scope, the keyword var is used, since to declare a variable in the global scope, it is omitted the same one:

var a = 5; // Variável "a" declarada no escopo local
b = 10; // Variável "b" declarada no escopo global

Example illustrating scope operation

a = 5;

primeira_funcao = function(){

var a = 15;

alert(a); // alerta 15

}

primeira_funcao(); // Chamada à primeira função

segunda_funcao = function(){

alert(a); // alerta 5

}

segunda_funcao(); // Chamada à segunda função

alert(a); // alerta 5

As seen in the example above, the variable a initially declared with the value of 5 , was alerted, in the second function as well as call outside the functions, with its original value, only being changed the value of the same in the the first function, where var a = 15; was declared by initiating another variable with the name a , but in the local scope, so when called alert(a); was warned 15 instead of 5 .

The syntax of the for is very well explained in the other answers, so I will not approach it here, good studies;)

    
24.09.2014 / 06:07
-1

I think your question is "why does it appear from 1 to 10 when I put it inside the keys and when I put it out it only shows 10"

In your example, FOR is adding +1 (such as i ++) to the variable "i" each time it runs in FOR, so basically the sum was done and then the value was shown, different from when it is inside the FOR that every +1 that happens it already invokes the "alert".

What happens inside the computer when you put the alert inside the for is:

i=0
Alert(0) //mostra mensagem
i=1 //0+1 = 1
alert(1)
i=2 //1+1 = 2
alert(2)
i=3 //2+1 = 3
alert(3)

and so on

In case of alert outside of what happens on the computer is as follows:

i=0
i=1 //0+1
i=2 //1+1
i=3 //2+1
i=4 //3+1
i=5 //4+1
i=6 //5+1

So basically what happens is that it sums everything up and then it shows (when ta outside of FOR) and when it's in, every time it adds 1 it will run the alert () also what will show the CURRENT number that is in the variable i ...

I hope you have understood the difference of using inside or outside the

    
06.10.2014 / 17:59