0

I'm making a game involving asteroids. I have a collision detection function that looks something like this:

function collisions(){
  for (j=asteroids.length-1;j>=0;j++){
    //do stuff with asteroids[j]
  }
}

I tried doing the collision math with the asteroids, but I got this error:

TypeError: Cannot read property 'x' of undefined

My main problem is that when I wrote:

console.log(asteroids[j])

It logged two values, the Asteroid object, and undefined. I thought maybe it was logging undefined from somewhere else, so I wrote:

console.log("1", asteroids[j], "2")

and it returned both the Asteroid object, and undefined, both with a "1" before and a "2" after. Does asteroids[j] have both values? What is happening here? How do I fix this?

Thanks in advance.

themousery
  • 23
  • 7
  • Possible duplicate of [Javascript loop through object array?](https://stackoverflow.com/questions/19529403/javascript-loop-through-object-array) and possibly [How to loop through an array containing objects and access their properties](https://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties) – Tigger Sep 30 '17 at 05:00
  • Shouldn't you be doing `j--` in the for loop? – Rajeev Ranjan Sep 30 '17 at 05:01

2 Answers2

2

You need to decrement (i--) the loop instead increment (i++).

for (j=asteroids.length-1;j>=0;j--){
  //do stuff with asteroids[j]
}
Sajib Khan
  • 22,878
  • 9
  • 63
  • 73
1

You start the loop with asteroids.length-1 which is the last element ant then increment j++ the index. This pushes you outside the array in the second iteration itself. Hence you get the second as undefined. Javascript does not throw ArrayIndexOutOfBound like errors. It has undefined which says it all. Hence you get an undefined for trying to access something out of bound of the array.

Rajeev Ranjan
  • 3,588
  • 6
  • 28
  • 52