Can an increment / decrement of a for loop be more than one?

Are there other ways to extend the for loop in Javascript besides i++ and ++i ? For example, I want to increase by 3 instead of one.

 for (var i = 0; i < myVar.length; i+3) { //every three } 
+58
javascript increment for-loop
09 Oct '12 at 23:16
source share
5 answers

Use the assignment operator += :

 for (var i = 0; i < myVar.length; i += 3) { 

Technically, you can place any expression that you want in the final expression of the for loop, but it is usually used to update the counter variable.

For more information about each step of the for loop, see the MDN article .

+132
Oct 09 '12 at 23:18
source share
  for (var i = 0; i < 10; i=i+2) { // code here }​ 
+7
Oct 09 '12 at 23:19
source share

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 .

Please note that operators and ++ variants are operators with side effects (you should avoid them if you do not use them as i+=1 , etc.):

  • ++i means i+=1; return i i+=1; return i
  • i++ means oldI=i; i+=1; return oldI oldI=i; i+=1; return oldI

Example:

 > i=0 > [i++, i, ++i, i, i--, i, --i, i] [0, 1, 2, 2, 2, 1, 0, 0] 
+6
Oct 09 '12 at 23:28
source share

Andrew Whitker's answer is correct, but you can use any expression for any part.
Just remember that the second (average) expression must be evaluated, so it can be compared with 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

 var i = 0; while( i < 10 ) { /* expression */ ++i; } 
+5
Oct 09 '12 at 23:32
source share

Of course you can. Others correctly pointed out that you need to do i += 3 . You cannot do what you posted, because everything you do adds i + 3 but does not return the result back to i . i++ is simply an abbreviation for i = i + 1 , similarly i +=3 is an abbreviation for i = i + 3 .

+1
May 24 '17 at a.m.
source share



All Articles