Esta tradução está incompleta. Ajude atraduzir este artigo.
A instrução for cria um loop que consiste em três expressões opcionais, dentro de parênteses e separadas por ponto e vírgula, seguidas por uma declaração ou uma sequência de declarações executadas em sequência.
Sintaxe
for ([inicialização]; [condição]; [expressão final]) declaração
inicialização- Uma expressão (incluindo expressões de atribuição) ou declarações variáveis. Geralmente usada para iniciar o contador de variáveis. Esta expressão pode, opcionalmente, declarar novas variáveis com a palavra chave var. Essas variáveis são não locais no loop, isto é, elas estão no mesmo escopo que o loop for está. O resultado desta expressão é descartado.
condição- Uma expressão para ser avaliada antes de cada iteração do loop. Se esta expressão for avaliada para true,
statementserá executado. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following theforconstruct. expressão final- An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of
condition. Generally used to update or increment the counter variable. declaração- A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement (
{ ... }) to group those statements. To execute no statement within the loop, use an empty statement (;).
Exemplos de uso
The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.
for (var i = 0; i < 9; i++) {
console.log(i);
// more statements
}
Optional for expressions
All three expressions in the head of the for loop are optional.
For example, in the initialization block it is not required to initialize variables:
var i = 0;
for (; i < 9; i++) {
console.log(i);
// more statements
}
Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.
for (var i = 0;; i++) {
console.log(i);
if (i > 3) break;
// more statements
}
You can also omit all three blocks. Again, make sure to use a break statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.
var i = 0;
for (;;) {
if (i > 3) break;
console.log(i);
i++;
}
Using for with an empty statement
The following for cycle calculates the offset position of a node in the [final-expression] section, and therefore it does not require the use of a statement or block statement section, an empty statement is used instead.
function showOffsetPos (sId) {
var nLeft = 0, nTop = 0;
for (var oItNode = document.getElementById(sId); // initialization
oItNode; // condition
nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent) // final-expression
/* empty statement */ ;
console.log("Offset position of \"" + sId + "\" element:\n left: " + nLeft + "px;\n top: " + nTop + "px;");
}
// Example call:
showOffsetPos("content");
// Output:
// "Offset position of "content" element:
// left: 0px;
// top: 153px;"
statement section, a semicolon is put immediately after the declaration of the cycle.Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 1st Edition. | Standard | Initial definition. |
| ECMAScript 5.1 (ECMA-262) The definition of 'for statement' in that specification. |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'for statement' in that specification. |
Standard |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |