2

I have Javascript code as follows:

addEventListener("keydown", function (e) {
    keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
    delete keysDown[e.keyCode];
}, false);    
if (81 in keysDown){
    doThisFunction() //q
} 

doThisFunction will be called when I press the q button on the keyboard. I found the line "81 in keysDown" to be quite interesting.

I was wondering if there was a way to say "if 81 is NOT in keysDown" so that I can detect a moment when q has been let go or when q is not pressed.

Thanks in advance!

Bruno Peres
  • 15,845
  • 5
  • 53
  • 89
TheShadeM
  • 45
  • 1
  • 1
  • 4

3 Answers3

11

Just use the negation operator:

if (!(81 in keydown)) …

Notice you need the additional grouping parenthesis to get the desired operator precedence.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

Yes you can by wrapping the whole conditional in parentheses and negating it, like so:

if(!(81 in keysDown)) {
    doThisFunction();
}
Thomas Maddocks
  • 1,355
  • 9
  • 24
1

Just get the index:

if(keysDown.indexOf(81) < 0){
    //code
}

Or if it is an object:

if (!(num in keysDown)) { ... }
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76