JJJollyjim
JJJollyjim

Reputation: 6237

Resetting the iterator in a for...in loop

This is part of the code I am using to draw some random circles:

if(circles.length != 0) { //1+ circles have already been drawn
  x = genX(radius);
  y = genY(radius);
  var i = 0;
  iCantThinkOfAGoodLabelName:
  for(i in circles) {
    var thisCircle = circles[i];
    if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) {
      //overlaps
    } else {
      //overlaps
      x = genX(radius);
      y = genY(radius);
      continue iCantThinkOfAGoodLabelName;
    }

    if(i == circles.length - 1) { //Last iteration
      //Draw circle, add to array
    }
  }
}

The problem is that when there is an overlap, the circle with the newly generated coordinates is not checked for overlap with the circles that the overlapping circle had already been checked with. I have tried setting i to 0 before using the continue statement but that did not work. Please help, I am really confused.

Upvotes: 2

Views: 6143

Answers (3)

Domenic
Domenic

Reputation: 112907

You should not use for ... in on arrays.

Use for(var i = 0; i < circles.length; ++i) instead. Then you can reset by setting i = 0.

Upvotes: 4

Ibu
Ibu

Reputation: 43850

Why not use a standard for loop

for (var i=0,l = circles.length;i < l; i++) {
   ....  

   if (i === l) {
     // draw
   }
}

Upvotes: 1

James Montagne
James Montagne

Reputation: 78710

I'm not fully understanding the question, but I do not believe you can reset the iterations of a for..in. You'll need to go to a for(var i=0;...;i++).

Upvotes: 0

Related Questions