如何在FOR循环中颠倒顺序 [英] How to reverse the order in a FOR loop
问题描述
var num = 10,
reverse = false; (i = 0; i< num; i ++){
console.log(i);
。
当 reverse 为false时,我希望它返回类似[0,1,2,3,4,5,6,7,8,9]
,但反向为真的,它应该返回[9,8,7,6,5,4,3,2,1,0]
哪一个是最有效的方法得到这个结果,而不是每次检查 reverse 在循环内是true还是false?
我不想这样做:
var num = 10,
reverse = false; (b)b
$ b为(i = 0; i if(反向)console.log(num-i)
else console.log(i)
}
我只想检查反向循环。
var num = 10,
reverse = false;如果(!反向)for(var i = 0; i< num; i ++)log(i);
。
else while(num--)log(num);
//避免重复,如果代码变长
function log(num){console.log(num); }
编辑:
正如下面的评论所指出的,如果 i
没有在其他地方声明,你不打算这么做global,然后声明它与你声明的其他变量。
如果你不想修改 num $ c的值$ c>,然后将它分配给
i
first。
var num = 10,
reverse = false,
i;如果(!反向)for(var i = 0; i< num; i ++)log(i);
。 //计数
else {var i = num; while(i--)log(i);} //倒数
函数log(num){console.log(num); }
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.
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 ); }
这篇关于如何在FOR循环中颠倒顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!