How to reverse the order in a FOR loop

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

    Roy's is similar to mine, but here's what I was thinking. I'll give you what I wrote in C# and how I think it translates to Javascript.

    C#

        int num = 10;
        bool reverse = true;
    
        for (int i = reverse ? num : 0; (reverse ? 0 : i) < (reverse ? i : num); i += reverse ? -1 : 1)
        {
            Console.Write((reverse ? i - 1 : i).ToString());
        }
        Console.ReadKey();
    

    Javascript

            var num = 10,
            reverse = true;
    
        for (int i = reverse ? num : 0; (reverse ? 0 : i) < (reverse ? i : num); i += reverse ? -1 : 1)
        {
            console.log(reverse ? i - 1 : i);
        }
    

    And here's another way
    Javascript

        var num = 10,
            reverse = false;
    
        for (int i = 0; i < num; i++)
        {
          console.log((reverse ? abs(-num + (i + 1)) : i));
    
        }
    

提交回复
热议问题