Repetition commands are used when we want a certain set of instructions to be executed a defined and/or indefinite number of times or while a condition is met.
In Java-script there are these repeat commands:
Do While
In this type of repetition the process is repeated as long as the condition is true. In the diagram below, the coding repeats until the number reaches 101. Then it exits the repetition and multiplies the number * 2.
In code it looks like this:
Repet: <div id="contador"></div><br> Result:<div id="resultado"></div> <script> var contador = 1; var resultado = 0; var numero = 1; do { numero += 1; contador += numero + '; '; } while (numero<=100); resultado=numero*2 document.getElementById('contador').innerHTML = contador; document.getElementById('resultado').innerHTML = resultado; </script>
Repet:
Result:
While
In this type of repetition, the process will be executed until the condition is satisfied, that is, it will only execute the commands within the repetition, while the condition is true. In the flow below, at each repetition, it adds number=number+2; And when the condition of number<50 arrives, as the result, it multiplies it by 2.
See the code:
Repet: <div id="contador"></div><br> Result:<div id="resultado"></div> <script> var contador = "0; "; var resultado = 0; var nuber = 0; while (number<50) { number += 2; contador += number + '; '; } resultado=number*2 document.getElementById('contador').innerHTML = contador; document.getElementById('resultado').innerHTML = resultado; </script>
Repet:
Result:
For
In this type of repetition the process is repeated until the specified condition is false. In the example below the repetition will happen until i is less than 9.
<br> <!--The id="counter3" and id="result3" divs will receive the results corresponding to what was defined in document.GetElementById --> Repet: <div id="contador3"></div><br> Result:<div id="resultado3"></div> <script> var result = ""; contador3=""; /* will repeat until i is less than 9 */ for (var i = 0; i < 9; i++) { /*concatenate the string count 3 by adding one; Example:0; 1; two; */ contador3 +=i +";"; /* concatenate the string result 3 and add > line"+1. Example: line 1, line2 */ resultado3 +="<br> line "+i; } /* defines that the object that has id="count3" and id="result" will display the information*/ document.getElementById('contador3').innerHTML = contador3; document.getElementById('resultado3').innerHTML = resultado3; </script>
Repet:
Result:
Espero que você tenha entendido a importancia destes tipos de comandos na programação