Can a for loop increment/decrement by more than one?
Solution 1:
Use the +=
assignment operator:
for (var i = 0; i < myVar.length; i += 3) {
Technically, you can place any expression you'd like in the final expression of the for loop, but it is typically used to update the counter variable.
For more information about each step of the for loop, check out the MDN article.
Solution 2:
A for
loop:
for(INIT; TEST; ADVANCE) {
BODY
}
Means the following:
INIT;
while (true) {
if (!TEST)
break;
BODY;
ADVANCE;
}
You can write almost any expression for INIT
, TEST
, ADVANCE
, and BODY
.
Do note that the ++
operators and variants are operators with side-effects (one should try to avoid them if you are not using them like i+=1
and the like):
-
++i
meansi+=1; return i
-
i++
meansoldI=i; i+=1; return oldI
Example:
> i=0
> [i++, i, ++i, i, i--, i, --i, i]
[0, 1, 2, 2, 2, 1, 0, 0]
Solution 3:
for (var i = 0; i < 10; i = i + 2) {
// code here
}
Solution 4:
Andrew Whitaker's answer is true, but you can use any expression for any part.
Just remember the second (middle) expression should evaluate so it can be compared to a boolean true
or false
.
When I use a for
loop, I think of it as
for (var i = 0; i < 10; ++i) {
/* expression */
}
as being
var i = 0;
while( i < 10 ) {
/* expression */
++i;
}