简体   繁体   English

JavaScript-是否可以在for循环中递减计数器?

[英]JavaScript - Is it possible to decrement counter within for loops?

I'm trying to iterate over an array and in certain situations need to decrement my counter. 我正在尝试遍历数组,并且在某些情况下需要减少我的计数器。

My goal is to rearrange divs into two columns with a fixed height. 我的目标是将div重新排列为具有固定高度的两列。

It looks like this: 看起来像这样:

var divs = document.getElementsByTagName('div');

for(var i = 0; i < divs.length; i++) {
    if(left column is not full) {
        left.append(divs[i]);
    }
    else if(right column is not full){
        right.append(divs[i]);
    }
    else {
        create 2 new columns (left & right);
        i--; //so that the element doesn't get lost
    }
}

I don't end up in an infinite loop, but the result isn't quite what i expected. 我不会陷入无限循环,但是结果与我预期的不一样。 Is there an error in my logic or is it simply impossible/not allowed to decrement the counter from within the loop? 我的逻辑中是否有错误,还是根本不可能/不允许从循环内递减计数器?

It is a bad practice to modify a counter within a loop. 在循环中修改计数器是一种不好的做法。

Use while instead. 改为使用while Then you will be able to define your custom counter modifying logics. 然后,您将能够定义您的自定义计数器修改逻辑。

For example, the snippet below removes all negative items from an array using the following algorithm: 例如,下面的代码片段使用以下算法从数组中删除了所有否定项:

  • if an item is positive - continue 如果一个项目为正-继续
  • otherwise, remove an item in position i 否则,请移除位置i中的项目

It isn't possible to do this with a for loop without either additional array or manual counter decrement, as for loop would skip the value after a removed one every time. 这是不可能用做这for循环而不任一附加的阵列或手动计数器减少,作为for循环每次移除一个后会跳过值。

 var items = [0, 3, 5, -3, -5, -7, 11]; var i = 0; while (i < items.length) { if (items[i] < 0) items.splice(i, 1); else i++; } document.body.innerText = JSON.stringify(items); 

you can decrement counters in for loops but you will find it hard to keep track on them. 您可以减少for循环中的计数器,但会发现很难跟踪它们。 for your case it's simply better to use a while loop. 对于您的情况,最好使用while循环。

how about this: 这个怎么样:

var i = 0;
while(i < length) {
    if(a) {
        //do something
        i++;
    }
    else {
        //do something else
        i--;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM