JSfiddle 数字猜谜游戏

JSfiddle number guessing game

我在 Jsfiddle 中制作了一个猜数游戏,我无法将随机数存储到数组中。我需要编程来拍摄一个随机数并存储它,直到猜到该数字或游戏结束

这是我的 fiddle link https://jsfiddle.net/e64gt4sv/ 任何帮助将不胜感激谢谢

HTML代码:

<h1>The Guesssing Game</h1> Pick a number between 1 and 1000:
<input id="myAssumption" type="text" />
<input type="submit" id="byBtn" onclick="checkMyAnswer()" value="Click To See If your Correct" />

Js代码:

    var numberOfSteps = 1;

function checkMyAnswer() {
  var actual = Math.floor(Math.random() * 1000) + 1;
    var myAnswer = document.getElementById("myAssumption").value; //getting user value

  if (myAnswer < actual) { //checking less tha answer
    alert("Guessed " + myAnswer + " too low");
    numberOfSteps++;
  } else if (myAnswer > actual) { //checking grater than answer
    alert("Guessed " + myAnswer + " too high");
    numberOfSteps++;
  } else { //you got answer
    alert("Guessed " + myAnswer + " Got it!!");
    alert("It tool " + numberOfSteps + " steps");
  }
}

我编辑了 jsfiddle。检查一下 https://jsfiddle.net/e64gt4sv/3/

var numberOfSteps = 1;
var actual = Math.floor(Math.random() * 1000) + 1;
var guesses = [];

function checkMyAnswer() {
    ...
}

Jeremy 是对的,每次调用 checkMyAnswer 时,都会重新生成实际号码。相反,如果你在函数外设置它,你仍然可以获得函数内的值,但它只会在每次实际 javascript 文件加载时设置(意味着每次加载/重新加载页面时)。

另外,我添加了一些东西来将每个猜测存储在一个数组中。数组 guesses 是一个全局变量,然后当您调用 checkMyAnswer() 时,通过

将用户输入的值添加到数组中
var myAnswer = document.getElementById("myAssumption").value; //getting user value
guesses.push(myAnswer);