How to reverse the order in a FOR loop

前端 未结 12 626
滥情空心
滥情空心 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:35

    Surely in a language like Javascript there must be a way to define a local function and use that in the loop?

    function SubtractFrom(val, subtractor) {
        return val - subtractor;
    }
    
    function PassThrough(val) {
        return val;
    }
    
    var num = 10;
    var processor = reverse ? SubtractFrom(num-1) : PassThrough;
    
    for (i = 0; i < num; i++) {
        console.log(processor(i));
    }
    

    Not knowing Javascript though, I don't know what actual form the function definitions would take.

提交回复
热议问题