Iladarsda
Iladarsda

Reputation: 10692

JavaScript for loop, regarding index

How to alter this loop, so that it runs for i = 12, 18, 24, 30 and 36 only?

for (var i = 12; i < 36; i++) {
   console.log(i);
}

Upvotes: 0

Views: 139

Answers (4)

Felix Kling
Felix Kling

Reputation: 816970

Alternatively (though not necessarily better):

for(var i, values = [12, 18, 24, 30, 36]; i = values.shift();) {
    console.log(i);
}

This shows that you do not need to have an increasing counter in a for loop.

Upvotes: 1

Greg B
Greg B

Reputation: 14898

The i++ in the for statement is what to do before the next iteration of the loop. So in the case of i++ we're incrementing the variable i by one. So if you want to increment by six then you need to add 6 to the variable which will give you:

for (var i = 12; i < 36; i += 6) {
    console.log(i);
} 

Next up, you want to include 36, so you need to change your condition (the bit of your loop that says i < 36) to include 36. This is really easy, you just need to change the "less than" to "less than or equal to" :

for (var i = 12; i <= 36; i += 6) {
    console.log(i);
} 

Upvotes: 3

Vala
Vala

Reputation: 5674

Instead of doing i++ in your loop, do i += 6. Like this:

for (var i = 12; i < 36; i += 6) {
    console.log(i);
}

Upvotes: 1

William Brendel
William Brendel

Reputation: 32207

for (var i = 12; i <= 36; i += 6) {

   console.log(i);

} 

Upvotes: 9

Related Questions