2

So, I have this function, which for some reason at some point starts throwing an "enemies[i] is undefined" error. The function is constantly called in the game loop.

function moveEnemies() {

  for(i = 0; i < enemies.length; i++) {
    enemies[i].y += FE_SPEED;
    enemies[i].c.attr("y", friends[i].y);
    if(enemies[i].y > 640)
      delete enemies[i];
  }

  for(i = 0; i < enemies.length; i++) {
    if(!enemies[i])
      enemies.splice(i, 1);
  }
}

What am I doing wrong?

mkkekkonen
  • 1,704
  • 2
  • 18
  • 35
  • `enemies.length` is a changing value since you call `delete enemies[i]` and `enemies.splice(i,1)`. You should instead keep changing a variable that updates the length of the list and break out of the loop when your loop counter is higher than this variable. – stackErr Feb 19 '16 at 15:34
  • 1
    @stackErr: No it does not change from the `delete` call. Of course, he shouldn't be using `delete` at all, but that's another story. – Bergi Feb 19 '16 at 15:35
  • @Bergi oops yes `delete` doesn't change it but `splice` does! – stackErr Feb 19 '16 at 15:38
  • I'm not sure this is an exact duplicate. The duplicate doesn't mention delete, and the question is not the same problem. The answer may be similar, but the question seems unique. – jamesmortensen Feb 19 '16 at 15:47

1 Answers1

0

You are altering the array inside the for loop.

enemies.splice(i, 1); is changing the length of the enemies

e.g.

var a = [1,2,3,4];
a.splice(1,2);

console.log( a.length ); // 2
Avraam Mavridis
  • 8,698
  • 19
  • 79
  • 133