-2

我目前正在用 Javascript 编写一个简单的程序。我不知道为什么程序不能正常工作。用户应该能够猜出一个数字,程序会告诉用户它需要猜高还是低。现在,它甚至没有给我第一个提示。谢谢大家的帮助。

<html>
  <head>
  </head>
  <body>
    <script>
      //Guessing Game
      function guessingGame() {
        var userNumber = prompt("Pick a number 1 through 1000!", "Type your number here");
        var computerNumber = Math.floor(Math.random() * 1000 + 1);
        var tries = 0;
        var done = false;
        while (done === false) {
          if (userNumber < computerNumber) {
            document.write("Your number was too low.");
            tries = tries + 1;
            userNumber = prompt("Please guess again", "Type your number here");
          } else if (userNumber > computerNumber) {
            document.write("Your number was too high.");
            tries = tries + 1;
            userNumber = prompt("Please guess again", "Type your number here");
          } else {
            document.write("Great Job!!! You guessed the number in " + tries + " tries!" );
            done = true;
          }
        }
      }
      guessingGame();
    </script>
  </body>
</html>
4

2 回答 2

2
document.write("Great Job!!! You guessed the number in " + tries " tries!" );

此行缺少+after tries。语法错误通常会导致整个 JavaScript 块被丢弃,因此没有任何运行。

if (userNumber < computerNumber) {

您还应该避免<在 JavaScript 代码中使用未转义的字符,因为它不能与 HTML 很好地混合。写要么

if (userNumber &lt; computerNumber) {

或者将整个脚本放入 CDATA 部分,以便允许使用未转义的尖括号。

<script>
// <![CDATA[

    /* code here, can use '<' freely */

// ]]>
</script>
于 2013-01-25T03:54:25.743 回答
2

您忘记了+该行中的其他串联:

document.write("Great Job!!! You guessed the number in " + tries " tries!" );

它应该是

document.write("Great Job!!! You guessed the number in " + tries + " tries!" );

修复了jsFiddle上的示例。

于 2013-01-25T03:54:34.993 回答