0

I have a piece of code that creates vertices in a loop.

for(var i=0; i<100; i++){
  graph.add_vertex();
}

and another piece of code that seeks to clear them

graph.clear();

A vertex calls the getId() function, which simply assigns a incremented number. add_vertex is the only function calling getId().

clear() looks something like this:

for(var i=0; i<graph.V.length; i++){
    console.log(graph.V[i]);
    graph.V[i].remove();
}

and the output lists every other vertex. What could cause an error like this?

Joshua M. Moore
  • 381
  • 6
  • 20
  • 2
    Possible duplicate of [javascript loop only applying to every other element](http://stackoverflow.com/questions/1457544/javascript-loop-only-applying-to-every-other-element) – JJJ Nov 06 '16 at 07:37
  • 1
    Looks like you are both incrementing your array index, and removing items from the array. That would cause you to skip every other member. – David784 Nov 06 '16 at 07:38
  • Simple solution, do your for loop in reverse. – Keith Nov 06 '16 at 07:42
  • To solve the issue @David784 mentioned you should start at the end of your array and then increment down, you can remove the object because it doesn't matter as you increment downward. `for(var i=graph.V.length; i>=0; i--) {//code}` – abc123 Nov 06 '16 at 07:42

0 Answers0