0

I have an array with keyboard combinations and this should validate to press keys exactly in the order of the array example

var listkeys = ['left', 'right', 'bottom', 'top'];

if(validate key){
    continue
}

the order of the array is important if they are wrong by pressing in the order of the arrows then as I continued not more and sends you an error

I am a newbie in javascript I hope I can help enormously grateful

4

1 回答 1

1

通常情况下,我不会回复那些要求“一劳永逸”解决方案的帖子,但我把它写了出来,不希望它浪费掉。这里有一些东西可以帮助您入门。

// Valid combination of keys
var valid_combo = ['left', 'right', 'bottom', 'top']; 

// Stack that stores the last 4 key inputs, including non-arrow keys
var history = [];  

// Maps arrow key direction strings to char code
var keys = []; 

keys[37] = 'left';
keys[38] = 'top';
keys[39] = 'right';
keys[40] = 'bottom';

$(window).keyup(function(e) {

    var key = e.which;

    if (key >= 37 && key <= 40) 
    {
        history.push(keys[key]);
    }
    else
    {
        history.push("derp");
    }

    if (history.length > 4) history.shift();

    // Array equality using Option 1 - http://stackoverflow.com/a/10316616/773702
    if (JSON.stringify(valid_combo) == JSON.stringify(history)) 
    {
        console.log("Valid key combination");
    }
});

在 jsFiddle 上查看它的实际效果

于 2013-05-13T22:05:16.290 回答