Declaração for do JavaScript
- Página anterior do...while
- Próxima página for...in
- Voltar à página anterior Manual de Referência Sentenças JavaScript
Definição e uso
A declaração for cria um loop que é executado enquanto a condição for verdadeira.
O loop continua a executar enquanto a condição for verdadeira. Ele para apenas quando a condição se torna falsa.
JavaScript suporta diferentes tipos de loops:
- for - loop de código executado várias vezes
- for/in - iteração de atributos de objetos
- for/of - Loop through the values of an iterable object
- while - Loop the code block when the specified condition is true
- do/while - Execute a code block once, then repeat the loop when the specified condition is true
Tip:Use the break statement to exit the loop, and use the continue statement to skip a value within the loop.
Exemplo
Loop the code block five times:
var text = ""; var i; for (i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; }
More TIY examples are at the bottom of the page.
Syntax
for (statement 1; statement 2; statement 3) { code block to be executed }
Parameter value
Parameter | Description |
---|---|
statement1 |
Optional. Execute before the loop (code block) starts. This statement is usually used to initialize counter variables. To initialize multiple values, separate each value with a comma. Comments:This parameter can be omitted. However, do not omit the semicolon ";" |
statement2 |
Optional. Define the condition for running the loop (code block). This statement is usually used to evaluate the condition of the counter variable. If it returns true, the loop will restart, and if it returns false, the loop will end. Comments:This parameter can be omitted. However, do not omit the semicolon ";". Moreover, if this parameter is omitted, it must provide a break within the loop. Otherwise, the loop will never end, which will cause your browser to crash. |
statement3 |
Optional. Execute after each loop (code block) execution. This statement is usually used to increment or decrement counter variables. Comments:This parameter can be omitted (e.g., increase/decrease the value within the loop). |
Technical details
JavaScript version: | ECMAScript 1 |
---|
More examples
Exemplo
The loop iterates over the array indices, collecting car names from the cars array:
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var text = ""; var i; for (i = 0; i < cars.length; i++) { text += cars[i] + "<br>"; }
Example explanation:
- First, we set a variable before the loop starts (var i = 0;)
- Then, we define the condition for the loop to run. As long as the variable is less than the length of the array (i.e., 4), the loop will continue
- The variable is incremented by one (i++) each time the loop executes
- Once the variable is no longer less than 4 (the length of the array), the condition is false, and the loop ends
Exemplo
Initialize multiple values in the first parameter:
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i; for (i = 0, len = cars.length, text = ""; i < len; i++) { text += cars[i] + "<br>"; }
Exemplo
Omit the first parameter (set the value before the loop starts):
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i = 2; var len = cars.length; var text = ""; for (; i < len; i++) { text += cars[i] + "<br>"; }
Exemplo
Use the continue statement - within the loop block, but skip the value "3":
var text = "" var i; for (i = 0; i < 5; i++) { if (i == 3) { continue; } text += "The number is " + i + "<br>"; }
Exemplo
Use a instrução break - execute um trecho de código, mas saia do laço quando o valor da variável i for igual a "3":
var text = "" var i; for (i = 0; i < 5; i++) { if (i == 3) { break; } text += "The number is " + i + "<br>"; }
Exemplo
Omita o segundo parâmetro. Neste exemplo, também usamos a instrução break para sair do laço quando i é igual a "3" (se omitir o segundo parâmetro, deve fornecer um break dentro do laço. Caso contrário, o laço nunca terminará e seu navegador falhará):
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var text = ""; var i; for (i = 0; ; i++) { if (i == 3) { break; } text += cars[i] + "<br>"; }
Exemplo
Percorra o índice do array em ordem decrescente (decremento negativo):
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var text = ""; var i; for (i = cars.length - 1; i >= 0; i--) { text += cars[i] + "<br>"; }
Exemplo
Omita o último parâmetro e aumente o valor dentro do laço:
var cars = ["BMW", "Volvo", "Saab", "Ford"]; var i = 0; var len = cars.length; for (; i < len;) { text += cars[i] + "<br>"; i++; }
Exemplo
Percorra os nós do objeto NodeList e altere a cor de fundo de todos os elementos <p> da lista:
var myNodelist = document.getElementsByTagName("P"); var i; for (i = 0; i < myNodelist.length; i++) { myNodelist[i].style.backgroundColor = "red"; }
Exemplo
Exemplo de laço aninhado (laço dentro de laço):
var text = ""; var i, j; for (i = 0; i < 3; i++) { text += "<br>" + "i = " + i + ", j = "; for (j = 10; j < 15; j++) { document.getElementById("demo").innerHTML = text += j + " "; } }
Suporte do navegador
instrução | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
para | Suporte | Suporte | Suporte | Suporte | Suporte |
Páginas relacionadas
Tutorial de JavaScript:Loop do JavaScript For
Manual de referência do JavaScript:Sentença do JavaScript for ... in
Manual de referência do JavaScript:Sentença do JavaScript break
Manual de referência do JavaScript:Sentença do JavaScript continue
Manual de referência do JavaScript:Sentença do JavaScript while
- Página anterior do...while
- Próxima página for...in
- Voltar à página anterior Manual de Referência Sentenças JavaScript