JS中的函数内的函数?

时间:2015-10-12 19:25:57

标签: javascript

我现在使用此代码的问题似乎是每个函数中的函数调用。它大致应该工作的方式是检查猜测的字母是否在单词数组中。我以后必须添加更多内容,以防止在猜测单词数组中的所有字母后循环。但就目前而言,我还没有能够让guessLetter函数第二次运行。



var word = ['p', 'h', 'o', 'n', 'e'];
var guess = [];
var nextGuess;

function guessLetter() {
  nextGuess = window.prompt("Make a guess:", "");

  if (nextGuess !== "") {
    guess.push(nextGuess);
    checkLetter(guess);
  } else
    console.log("No guess made.");
}

function checkLetter(guess) {
  var i = 0;
  while (i < word.length) {
    console.log('In checkLetter. guess index=' + guess[guess.length - 1] + ' guess=' + guess);
    if (word[i] == guess[guess.length - 1]) {
      console.log('In if of checkLetter');
      console.log('Current guessed letters: ' + guess + '. Found letter: ' + guess[guess.length - 1]);
    }
    i++;
  }
  guessLetter();
}

guessLetter();
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

也许这对你有所帮助,我使用了一个对象来解决这个问题:https://jsfiddle.net/mig1098/r33up7p7/

var getletters = {
    word : ['p', 'h','o','n','e'],
    guess : [],
    nextGuess : "",//letter
    count:0,
    guessLetter: function() {
        this.nextGuess = window.prompt("Make a guess:","");
        if (this.nextGuess !== "" && this.nextGuess !== false && this.nextGuess !== null) {
            this.guess.push(this.nextGuess);
            this.checkLetter();
        }else{
            console.log("No guess made.");
        } 
    },
    checkLetter() {
        for (i in this.word) {
            console.log('In checkLetter. guess index=' + this.guess[this.guess.length-1] + ' guess=' + this.guess);
            if (this.word[i] == this.guess[this.guess.length-1]) {
                console.log('In if of checkLetter');
                console.log('Current guessed letters: ' + this.guess + '. Found letter: ' + this.guess[this.guess.length-1]);
                this.count += 1;
            }
        }
        console.log('count hits:'+this.count);
        if(this.count == this.word.length){
            alert('you guess the letters: '+this.word);
        }else{
            this.guessLetter();
        }
    }
};
getletters.guessLetter();