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,479
  • 5
  • 47
  • 80
TheShadeM
  • 35
  • 1
  • 4

3 Answers3

5

Just use the negation operator:

if (!(81 in keydown)) …

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

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
1

Just get the index:

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

Or if it is an object:

if (!(num in keysDown)) { ... }
A.J. Uppal
  • 18,339
  • 6
  • 41
  • 73
1

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

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