-1

I am very new to Javascript and am trying to translate a game i made in python into javascript. I am currently trying to get keyboard input for the game. Whenever i run this however it gives me the following error: Uncaught TypeError: Cannot read property '0' of undefined(at line 4 in this example)

Board is a 2d array used to store the board and i have tested that before the addEventListener statement Board is not undefined.

Why is this error happening and what should i do to fix it. As mentioned before i am a complete beginner at javascript so simple explanations would be greatly appreciated. Kind regards

document.addEventListener('keydown', function(event){
   if(event.keyCode == 65){
      console.log(Board)
      Board[this.block1[0]][this.block1[1]]=null;
      Board[this.block2[0]][this.block2[1]]=null;
      Board[this.block3[0]][this.block3[1]]=null;
      Board[this.block4[0]][this.block4[1]]=null;
Meyer
  • 13
  • 4
  • 1
    Can you post a whole class? Because you use variables that we can't see – blazej Jun 14 '21 at 21:23
  • You should check if `this.block1` is undefined. – Nathan Jun 14 '21 at 21:24
  • It's telling you `this.block1` is undefined (or `this.block2`, `this.block3`, or `this.block4`). Likely because `this` is not what you think it is due to the function being an event handler. – Heretic Monkey Jun 14 '21 at 21:25
  • Th error is most likely caused by trying to access `this.block1[0]` when `this.block1` is `undefined`. The reason is that `this` probably isn't pointing at the thing you think it it. Using `this` can be tricky. `this` is probably pointing to `document`. –  Jun 14 '21 at 21:25
  • I've just checked and it tuns out that this.block1 was in fact undefined. – Meyer Jun 14 '21 at 21:28
  • blazej how would I do that as stack overflow has a character limit? – Meyer Jun 14 '21 at 21:29
  • You can edit your question at any time. There's a bunch of links directly below it. Post only relevant code, that should easily fit the limit. –  Jun 14 '21 at 21:55

1 Answers1

-2

this in your code is not what you expect it to be. If block1 etc are local variables, reference them without this.. If they are members of your encapsulating object, change your callback function to use arrow syntax to let this reference your object: document.addEventListener('keydown', event => { /*...*/ })