How to reverse the order in a FOR loop
var num = 10,
reverse = false;
for (var i = 0, n = reverse?num-1:0, d = reverse?-1:1; i < num; i++, n+=d) {
console.log(n);
}
This is equivalent to the following, which is more readable, but less compact:
var num = 10,
reverse = false;
var start = reverse ? num-1 : 0,
end = reverse ? -1 : num,
step = reverse ? -1 : 1;
for (var i = start; i != end; i += step) {
console.log(i);
}
Edit:
Actually, these two solutions are not identical, because the first one has an additional increment operation. Still, it is negligible from performance point of view. If you really want to get a compact solution that has the best performance, you can do the following (not for the faint of heart):
var num = 10,
reverse = false;
for (var r=reverse, i=r?num-1:0, n=r?-1:num, d=r?-1:1; i!=n; i+=d) {
console.log(i);
}
This has the advantage of having a single control structure, a single test in each loop, and a single iterator addition. It is not as fast as having an iterator increment/decrement, but only marginally so.
var num = 10,
reverse = false;
if(!reverse) for( var i=0;i<num;i++) log(i);
else while(num-- ) log(num);
// to avoid duplication if the code gets long
function log( num ) { console.log( num ); }
EDIT:
As noted in the comments below, if i
is not declared elsewhere and you do not intend for it to be global, then declare it with the other variables you declared.
And if you don't want to modify the value of num
, then assign it to i
first.
var num = 10,
reverse = false,
i;
if(!reverse) for(var i=0;i<num;i++) log(i); // Count up
else {var i=num; while(i--) log(i);} // Count down
function log( num ) { console.log( num ); }
Try use 2 loops:
if (reverse) {
for(i=num-1;i>=0;i--){
console.log(i)
}
}
else {
for(i=0;i<num;i++){
console.log(i)
}
}