Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the order in a FOR loop

I've a simple FOR statement like this:

var num = 10,
    reverse = false;

for(i=0;i<num;i++){
    console.log(i);
}

when reverse is false I want it to return something like [0,1,2,3,4,5,6,7,8,9]

but, when reverse is true, it should return [9,8,7,6,5,4,3,2,1,0]

Which is the most efficient way to get this result, without checking every time if reverse is true or false inside the loop?

I don't want to do this:

var num = 10,
    reverse = false;

for(i=0;i<num;i++){
    if(reverse) console.log(num-i)
    else console.log(i)
}

I would like to check reverse only one time outside the loop.

like image 989
Raspo Avatar asked Aug 27 '10 16:08

Raspo


People also ask

How do you reverse a list in a for loop in Python?

Python comes with a number of methods and functions that allow you to reverse a list, either directly or by iterating over the list object. You'll learn how to reverse a Python list by using the reversed() function, the . reverse() method, list indexing, for loops, list comprehensions, and the slice method.


2 Answers

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 ); }
like image 72
user113716 Avatar answered Oct 08 '22 21:10

user113716


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)
    }
}
like image 43
Ivan Nevostruev Avatar answered Oct 08 '22 20:10

Ivan Nevostruev