JavaScript:在键入前一个数组上的所有单词后显示单词的下一个索引

时间:2016-06-11 19:47:57

标签: javascript

我正在制作一个游戏,其中从页面顶部到页面底部将一系列单词设置为动画,并且用户必须在它们到达底部之前键入所有单词。在键入一组上的所有单词后,我一直在改变单词集。这是我的代码。

JS:

var word = ""; // what the user types
var targets = [["hey", "sup", "nothing", "memories", "man"], ["next", "level"]]; // array of words
var wordTyped = document.getElementById("wordtyped"); // div where it shows what the user typed
var wordlist = document.getElementById("wordlist"); // div where the array of words are displayed
var arrindex = 0;

// display the words in a div called indword. erase the current wordlist, update it with the new wordlist.
function displayWords(arr) {
    wordlist.innerHTML = "";
    for(var i=0; i < arr.length; i++) {
        wordlist.innerHTML += "<div class='indword'>"+arr[i]+"</div>";
        wordlist.innerHTML += "   ";
    }
}


// this is the game loop
function gameloop(arrindex) {

    displayWords(targets[arrindex]); // initially display all the words in     the array

    // listen for typing events
    document.body.addEventListener('keypress', function(e) {

        word += String.fromCharCode(e.keyCode); // this is what the user types
        wordTyped.innerHTML = word; // show what the user is typing on the div
        console.log(word);

        // this whole thing is to check if the word that the user typed is in the array targets
        var index = targets[arrindex].indexOf(word); 

        if (index > -1) {
            console.log("success");

            targets[arrindex].splice(index, 1); // if what the user types exists in targets, delete that from the array

            displayWords(targets[arrindex]); // then remove the existing array and display the new array.
            word = ""; // reset user input
            wordTyped.innerHTML = word;
        }

    });
}

gameloop(arrindex);

HTML:

<div class="container">
    <div id="wordlist" class="godown"></div>
</div>

这是整件事。 http://codepen.io/davegumba/pen/OXMKOj

我尝试将游戏循环包装在这样的闭包中:

for(var i=0; i < targets.length; i++) {
    (function gameloop(arrindex) {...
    })(i);
}

但它直接指向数组的最后一个索引,并且它复制了我输入的所有字母,因此输入单词“next”将改为输出“nneexxtt”。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你可以做几件事。

使用指针,然后在完成部分指针时更新指针。

var pointer = 0;
//when work is matched, remove it from the array, and when that array is empty, increment the pointer
if(arr[pointer].length == 0){
    pointer++;
}

或者您使用像array.shift()这样的数组函数;它在删除数组时返回数组的第一个元素。因此,每当您的工作数组为空时,请转到下一个。

var targets = [["one", "two", "three"], ["four","five","six"]];
var arr = targets.shift(); //now ["one", "two", "three"];

//when matched a word in the list.. trigger this function
function matchedWord(typedWord){
   arr.splice(arr.indexOf(typedWord),1);

   if(arr.length == 0){
     if(targets.length>0)
       arr = targets.shift(); //now ["four", "five", "six"]
     } else { 
       //you win
     }
   }
}

我希望这就是你要找的东西。