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.
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.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With