How to reverse the order in a FOR loop

前端 未结 12 578
滥情空心
滥情空心 2020-12-31 06:16

I\'ve a simple FOR statement like this:

var num = 10,
    reverse = false;

for(i=0;i

when rever

12条回答
  •  时光取名叫无心
    2020-12-31 06:41

    I just came across the need for this the other day. Here's how I did it:

    var num = 10,
        i = 0,
        direction = 1, 
        reverse = false;
    
    if(reverse)
        i = num + (direction = num = -1);
    
    for(; i !== num; i += direction) {
        console.log(i);
    }
    

    No need for separate loops, and no need to do math to calculate the proper i in the loop.

    So if reverse is true...

    • i (which represents our first item) becomes num - 1, so we're now starting on what would have been the last item

    • num (which represents out of bounds) becomes -1, so we're now stopping on what would have been the first item

    • direction is -1, which means it will decrement when we do i += direction

    So by swapping our starting point with our ending point and changing the alteration of i from 1 to -1, we'll be going up or down based on those modifications.

提交回复
热议问题