0

So I've been trying to debug a physics engine I'm writing, and for a multi-dimensional spatial hashmap I'm needing to allocate a 2D array of arrays.

Why does this code give me "Cannot read property 'push' of undefined"? Is there something happening in the line between my if statements and my trying to push on to the array?

EDIT "this" refers to a PhysicsEngine instance, it keeps a reference to the "entities" array as well as a "hashmap" array.

function PhysicsEngine(game) {
    this.game = game;
    this.entities = [];
    this.hashmap = createArray(32, 32);
}

for(var i = 0; i < this.entities.length; i++) {
    //Array item may not be a Simulateable Entity
    //this.entities[i].simulatePhysics(this);
    this.entities[i].ResolveCollisions();
    this.entities[i].Move();
    hmx = Math.round(Math.abs(this.entities[i].x/32));
    hmy = Math.round(Math.abs(this.entities[i].y/32));

    if(!logged) {
      console.log(this.hashmap);
      console.log(this.entities[i]);
      console.log(i, hmx, hmy);
      console.log(this.hashmap[hmx], this.hashmap[hmy]);
      logged = true;
    }

    if(!Array.isArray(this.hashmap[hmx])) {
      this.hashmap[hmx] = [];
      if(!Array.isArray(this.hashmap[hmx][hmy])) {
        this.hashmap[hmx][hmy] = [];
      }
    }

    this.hashmap[hmx][hmy].push(this.entities[i]);
}
8
  • 1
    Nice one. Can you kindly explain the this used here with a reference to your full code? Commented Dec 18, 2015 at 14:39
  • 2
    What if hmx is an array, but hmy isn't? Commented Dec 18, 2015 at 14:40
  • Where is this.hashmap defined? Commented Dec 18, 2015 at 14:41
  • 2
    @AndrueAnderson: Read carefully and figure out when the second if will run Commented Dec 18, 2015 at 14:46
  • 2
    No coffee?! That's completely irresponsible! Bits could have died! Commented Dec 18, 2015 at 14:49

1 Answer 1

2

I think that this code:

this.hashmap[hmx] = [];
      if(!Array.isArray(this.hashmap[hmx][hmy])) {
        this.hashmap[hmx][hmy] = [];
      }

is not correct. In particular, the "if" condition tests whether this.hashmap[hmx][hmy] is an array. The problem is that this.hashmap[hmx]=[] (as you have set one line before), so this.hashmap[hmx][hmy] is undefined and javascript throws an error "Undefined is not an object".

Maybe is this the problem?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that was the problem. Although I can't actually give you an upvote here because someone previously answered the same thing in the comments above. I do appreciate your time though.

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.