Reputation: 177
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
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
Reputation: 386868
You could use a value for adding
for (var i = 0, offset = something ? 1 : -1; i < 10; i += offset) {
// ...
}
Upvotes: 2