为什么会“中断”?不允许我像应该退出循环吗?

时间:2019-01-07 21:18:19

标签: javascript

我正在尝试学习JavaScript,并且正在创建一个基本的hang子手游戏。但是,尝试跳出循环时,我总是收到错误消息。我无法终生解决。

在此先感谢您的帮助。

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 === null) {
  break;
} 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);

3 个答案:

答案 0 :(得分:1)

将中断置于循环内

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 === null) {
    break;
} 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);

答案 1 :(得分:0)

如果没有看到其余的代码来了解范围,我会认为您使用的break不正确。相反,您应该使用return。

中断在循环内部使用(用于,同时,用于输入,切换等)。 如果返回,则使用as return从函数返回,如果阻塞并且可以返回值或不返回值。

if (guess === null) {
    return;

答案 2 :(得分:0)

JavaScript中的中断仅用于循环,而不是if语句,因此在运行代码时会收到该错误消息。其次,由于您无法停止警报而无法在提示中输入任何内容,因此while循环变为无限循环 我会这样重写它:

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);