Why does “break;” not allow me to exit my loop like it should?

后端 未结 3 1795
死守一世寂寞
死守一世寂寞 2021-01-29 16:33

I\'m trying to learn javascript and am creating a rudimentary hangman game. However, I keep getting an error when trying to break out of my loop. I can\'t figure it out for the

3条回答
  •  故里飘歌
    2021-01-29 16:42

    Break in javascript is only for loops, not if statements so you will get that error message when running your code. Secondly, the while loop becomes an infinite loop as you are not able to stop the alerts to enter anything into the prompt I would rewrite it like this:

    var words = [
            "javascript",
            "monkey",
            "amazing",
            "pancake"
        ];
    var word = words[Math.floor(Math.random() * words.length)];
    var answerArray = [];
    
    for (var i = 0; i < word.length; i++) {
            answerArray[i] = "_";
        }
    
    var remainingLetters = word.length;
    while (remainingLetters > 0) {
            alert(answerArray.join(" "));
            var guess = prompt("Guess a letter, or click Cancel to stop playing.");
            if(!guess){
              alert('Please enter a letter!')
            }
            else if(guess.length != 1) {
              alert('Please enter a single letter!')
            }
            else {
                for (var j = 0; j < word.length; j++) {
                if (word[j] === guess) {
                   answerArray[j] = guess;
                    remainingLetters--;
                  } 
                }
            }
        }
    
    alert(answerArray.join(" "));
    alert("Good job! The answer was " + word);
    

提交回复
热议问题