Google Chrome is throwing “Uncaught TypeError: Cannot set property ‘isDown’ of undefined” but it doesn’t look like anything is wrong with my code!
Important part of my variable array:
KEY = {
UP: 38,
DOWN: 40,
W: 87,
S: 83,
D: 68
}
pingpong = {
fps: 60,
pressedKeys: [],
complete: false,
}
Key listener initialization (this is where the error is thrown):
for (var keyCode in KEY) {
if (KEY.hasOwnProperty(keyCode)) {
pingpong.pressedKeys[KEY[keyCode]] = {
isDown: false,
wasDown: false
};
}
}
$(document).keydown(function(e) {
pingpong.pressedKeys[e.which].isDown = true;
});
$(document).keyup(function(e) {
/* This line is the issue */ pingpong.pressedKeys[e.which].isDown = false;
});
Any Ideas?
The problem is that you’re trying to access an element of the
pressedKeysarray which does not exist. For example, if we pressed the “a” key:When you initialize your array you only create elements for the properties of the
KEYobject:So
pressedKeysonly contains 5 elements, corresponding to the properties ofKEY. Note that a TypeError is also thrown in thekeydownevent handler, as well askeyup.To fix it, you could check that
e.whichis in theKEYSobject in the event handler functions. If it’s not, just ignore it. Something like this perhaps (there may be a better way, this is just what came to mind first):