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.

2

2 Answers 2

2

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

for (j=asteroids.length-1;j>=0;j--){
  //do stuff with asteroids[j]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you haha, I usually do, it just completely whoosed me here.
It is ok ... :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.