Prince Singh
Prince Singh

Reputation: 177

How can i use a variable to increment or decrement in a for loop?

if (something) {
  increment = 'i++'
} else {
  increment = 'i--';
}

for (var i = 0; i < 10; increment) {
  ...
}

Obviously I cannot use a string to increment or decrement. So, what should I do instead?

Upvotes: -1

Views: 114

Answers (2)

Albert Ko
Albert Ko

Reputation: 170

i += change

is probably the best way

But probably in most cases you can just use your original with increment and calculate the index you need, which would also work for more complicated situations i.e.

for (var i = 0; i < 10; i++) {
  var j;
  if(something) {
    j = -i
  } else {
    j = i
  }
  // use j from here on out
}

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

You could use a value for adding

for (var i = 0, offset = something ? 1 : -1; i < 10; i += offset) {
    // ...
}

Upvotes: 2

Related Questions