最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Resetting the iterator in a for...in loop - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Jun 18, 2011 at 4:29 JJJollyjimJJJollyjim 6,23719 gold badges58 silver badges79 bronze badges 2
  • can yuo create a jsfiddle for this? – Ibu Commented Jun 18, 2011 at 4:32
  • Okay... jsfiddle/evQ8a – JJJollyjim Commented Jun 18, 2011 at 4:34
Add a ment  | 

3 Answers 3

Reset to default 4

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.

Why not use a standard for loop

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

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

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++).

发布评论

评论列表(0)

  1. 暂无评论