如何要求用户猜测1到1000之间的数字

And*_*rew 2 javascript

我正在尝试编写一些javascript代码,要求用户猜测1到1000之间的数字并将其输入到提示框中.如果用户猜对了,会弹出一个警告框,说明他们做对了.如果他们猜错了,会弹出另一个警告框,说他们错了,再试一次.

这里的问题是我不知道我必须做什么才能使代码无限循环,直到他们得到正确的答案.这是我到目前为止所拥有的:

var a = 489; // the number that needs to be guessed to win the game.

//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");

// if/else statement that test if the variables are equal.
if (b == a) {
    alert("You're right!");
} else {
    alert("Incorrect! Try again!");
}
Run Code Online (Sandbox Code Playgroud)

Dow*_*oat 5

数字匹配

基本上,当你创建时prompt,它返回一个字符串或文本,而不是一个数字.要解决这个问题,请执行:

if (parseInt(b,10) === a) {
    //Code
}
Run Code Online (Sandbox Code Playgroud)

其他方法

他们有很多方法可以解析数字.这里还有一些:

parseFloat(b); // Also parses decimals: '5.3' -> 5.3
Run Code Online (Sandbox Code Playgroud)
parseInt(b, 10); // Gives an integer (base 10): '5.3' -> 5
Run Code Online (Sandbox Code Playgroud)
+b; // A very 'short' way; '5.4' -> 5.4
Run Code Online (Sandbox Code Playgroud)
Number('5.4e2'); // Number case: '5.4e2' -> 540
Run Code Online (Sandbox Code Playgroud)

循环

现在重复?让它循环!

var a = 432;

while (true) {

   var b = prompt("Enter a number in between 1 and 1000");

   if (b == a){
        alert("You're right!");
        break; // Stops loop
    } else if (!b) { break; } 
    else {
        alert("Incorrect! Try again!");
    }
}
Run Code Online (Sandbox Code Playgroud)

不知道为什么,但有些人讨厌while true循环.只要您正确编码,它们不应该引起任何问题


随机数

你可以使用随机数Math.random.

var min = 1,
    max = 1000;
Math.floor(Math.random() * (max - min + 1)) + min;
Run Code Online (Sandbox Code Playgroud)

如果你像我一样想要短代码,你可以通过以下方式缩短代码:

Math.floor(Math.random() * (999)) + 1;
Run Code Online (Sandbox Code Playgroud)

现在都在一起了!

var a = Math.floor(Math.random() * (999)) + 1;

while (true) {

  var b = prompt("Enter a number in between 1 and 1000");

  if (b == a) {
    alert("You're right!");
    break; // Stops loop
  } else if (!b) {
    alert("The Correct Answer was: " + a); //Shows correct answer
    break;
  } else {
    alert("Incorrect! Try again!");
  }
}
Run Code Online (Sandbox Code Playgroud)