Javascript 如何反转 FOR 循环中的顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3586304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:18:53  来源:igfitidea点击:

How to reverse the order in a FOR loop

javascriptperformancefor-loop

提问by Raspo

I've a simple FOR statement like this:

我有一个简单的 FOR 语句,如下所示:

var num = 10,
    reverse = false;

for(i=0;i<num;i++){
    console.log(i);
}

when reverseis false I want it to return something like [0,1,2,3,4,5,6,7,8,9]

reverse为 false 我希望它返回类似 [0,1,2,3,4,5,6,7,8,9]

but, when reverseis true, it should return [9,8,7,6,5,4,3,2,1,0]

但是,当reverse为真时,它应该返回 [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 reverseis true or false inside the loop?

哪个是获得此结果的最有效方法,无需每次都检查循环内的reverse是真还是假?

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 reverseonly one time outside the loop.

我只想在循环外检查一次反向

回答by user113716

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 iis not declared elsewhere and you do not intend for it to be global, then declare it with the other variables you declared.

正如下面的评论中所指出的,如果i没有在其他地方声明并且您不打算将其设为全局,则使用您声明的其他变量声明它。

And if you don't want to modify the value of num, then assign it to ifirst.

如果您不想修改 的值num,则将其分配给i第一个。

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 ); }

回答by Ivan Nevostruev

Try use 2 loops:

尝试使用 2 个循环:

if (reverse) {
    for(i=num-1;i>=0;i--){
        console.log(i)
    }
}
else {
    for(i=0;i<num;i++){
        console.log(i)
    }
}

回答by Roy Sharon

var num = 10,
    reverse = false;

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

This is equivalent to the following, which is more readable, but less compact:

这等效于以下内容,它更具可读性,但不那么紧凑:

var num = 10,
    reverse = false;

var start = reverse ? num-1 : 0,
    end   = reverse ? -1 : num,
    step  = reverse ? -1 : 1;
for (var i = start; i != end; i += step) {
    console.log(i);
}

Edit:
Actually, these two solutions are not identical, because the first one has an additional increment operation. Still, it is negligible from performance point of view. If you really want to get a compact solution that has the best performance, you can do the following (not for the faint of heart):

编辑:
实际上,这两个解决方案并不相同,因为第一个解决方案有一个额外的增量操作。尽管如此,从性能的角度来看,它可以忽略不计。如果您真的想获得具有最佳性能的紧凑解决方案,您可以执行以下操作(不适合胆小的人):

var num = 10,
    reverse = false;

for (var r=reverse, i=r?num-1:0, n=r?-1:num, d=r?-1:1; i!=n; i+=d) {
    console.log(i);
}

This has the advantage of having a single control structure, a single test in each loop, and a single iterator addition. It is not as fast as having an iterator increment/decrement, but only marginally so.

这具有单个控制结构、每个循环中的单个测试和单个迭代器添加的优点。它没有迭代器递增/递减那么快,但只是略微如此。

回答by Jerome

var start; var end; var inc;
if (reverse) {
    start = num-1; end = 0; inc = -1;
}
else {
    start = 0; end = num-1; inc = 1;
}
for(i=start;i!=end;i+=inc){
    console.log(i)
}

回答by Jerome

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 iin the loop.

不需要单独的循环,也不需要做数学计算来计算i循环中的正确值。

So if reverseis true...

所以如果reversetrue...

  • 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

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

  • i(代表我们的第一个项目)变成num - 1,所以我们现在从最后一个项目开始

  • num(代表越界)变成-1,所以我们现在停在第一个项目上

  • directionis -1,这意味着当我们这样做时它会递减i += direction

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

因此,通过将起点与终点交换并更改ifrom1到的更改-1,我们将根据这些修改上升或下降。

回答by Mike Dunlavey

Here's how I've always done reverse loops:

这是我一直以来做反向循环的方式:

for (i = num; --i >= 0; ) ...

回答by Bernard

I think this meets your requirements:

我认为这符合您的要求:

var num = 10;
var reverse = false;
var diff = 0;

if (reverse) {
    diff = num - 1;
}

for (i = 0; i < num; i++) {
    console.log(Math.abs(diff - i));
}

回答by XstreamINsanity

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# 写的东西,以及我认为它是如何转换成 Javascript 的。

C#

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

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

这是另一种方式
Javascript

    var num = 10,
        reverse = false;

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

    }

回答by abele

It seems to work:

它似乎有效:

  var num = 10;
  var z = 1;
  var k = -10;
  if (reverse ){
    k = -1;
    z = -1;
  }
  for(int i = 0; i < 10; i++){
    console.log(num+i*z+k);
  }

回答by dash-tom-bang

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

当然,在像 Javascript 这样的语言中,必须有一种方法来定义本地函数并在循环中使用它吗?

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.

虽然不知道 Javascript,但我不知道函数定义会采用什么实际形式。