简体   繁体   English

控制多个按键时出现奇怪的情况

[英]Strange occurrences with controlling multiple keys being held down

With the below code, when a key is pressed its keycode is pushed to the keymap array if it's not already there and when a key is let up its keycode is taken out of the array. 使用下面的代码,当一个键被按下时,如果它的键代码尚不存在,则将其推入键映射数组;当释放一个键时,其键代码将从数组中取出。 When testing this out by constantly shoving the keymap array to the console, I found some strange things. 通过不断地将键映射数组推到控制台进行测试时,我发现了一些奇怪的东西。

var keymap = [];

$(window).keydown(function(e) {
    if($.inArray(e.keyCode,keymap) == -1) {keymap.push(e.keyCode);}
});

$(window).keyup(function(e) {
    for(i = 0;i < keymap.length;i++) {
        if(keymap[i] = e.keyCode) {keymap.splice(i,1);}
    }
});

setInterval(function() {console.log(keymap);},100);
  1. If I hold down a and d at the same time their keycodes are present in keymap, then if I hold down w all three of their keycodes are present. 如果我同时按下a和d,则它们的键码都出现在键映射中,那么如果我按下w,则它们的所有三个键码都都出现了。 Now when I let go of w it's removed from the array, but so is d even though I'm still holding down d. 现在,当我放开w时,它已从数组中删除,即使我仍然按住d,d也是如此。

  2. I then found that I can hold down a, w, and d and they'll all be put into keymap, but it will not put w, a, and s in keymap when I hold them down. 然后,我发现可以按住a,w和d并将它们全部放入键盘映射,但是当我按下它们时,不会将w,a和s放入键盘映射。 A combination of two of these will be put in, but the third will not. 将其中的两个结合在一起,但第三个则不会。

Can anyone tell me what's going on? 谁能告诉我怎么回事?

Your comparison is an assignment actually. 您的比较实际上是一项任务。 Change if(keymap[i] = e.keyCode) to if(keymap[i] = e.keyCode)更改为

if (keymap[i] == e.keyCode)
//             ^

Also, you should use local variables: 另外,您应该使用局部变量:

for(var i = 0; …
//  ^^^

And while it shouldn't matter for your array where items are supposed to be unique, you need to decrease the counter variable i after you remove an item or you skip to check the next one otherwise: 虽然对于您的数组来说项目应该是唯一的并不重要,但是在删除项目之后您需要减小计数器变量i ,否则请跳过以检查下一个项目:

keymap.splice(i--,1)
//             ^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM