我正在嘗試確定用戶是否在特定時間內鍵入了一組特定字符。檢測特定時間內是否鍵入了某些字符
我做了一些工作,我想,但我知道它不是很好,因爲它使用全局變量toMatch。我用setInterval聲明瞭它,但沒有var
關鍵字。雖然範圍的想法令我感到困惑,但我正在努力學習,並且我想知道是否有人可以提供更好的方法來做到這一點?
//set the toMatch array equal to the character codes for the word 'test'
//reset it to its original value every 2seconds
var matchTime = setInterval(function(){ console.log('toMatch reset'); toMatch = [84,69, 83, 84];}, 2000);
document.addEventListener("keydown", function(e){
var key = e.which;
findMatches(key);
});
function findMatches(key){
//if the key is in the first position in the array, remove it
if (key == toMatch[0]){
toMatch.shift();
}
console.log(toMatch);
//if all shifted out, clear the interval
if (toMatch.length == 0) {
window.clearInterval(matchTime);
alert('typed \'test\' within two seconds');
}
}
謝謝
爲什麼不能在'findMatches'中定義? – 2013-02-19 22:46:32
@Nicholas使用array.shift()是什麼使用呢? – luckystars 2013-02-19 22:52:39