简单的JavaScript功能,仅要求用户正确答案5次



我正在尝试使用JavaScript开发一个非常简单的功能,该功能提示用户输入一个数字,然后给他们5个机会来猜测给定数字的平方。

因此,例如,如果用户在第一个提示中排名6,则应在第二个提示中输入36,但是如果他们无法做到正确,他们会遇到一个错误,说猜测数字是错误的。而且它们仅限于5个机会,因此此之后,该程序不会再次提示用户。

我试图做这样的事情以使事情变得简单:

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries");
if (input2 == input*input) {
    alert("Good!");
} else {
    prompt("Wrong, enter again!");
}

我在这里正确的道路吗?我的意思是它没有做我想做的事情,但是我真的很陷入困境。不知道如何循环5次,或者下一步该做什么。

尝试此

function guessSquare() {
    var input = parseInt(window.prompt("Enter a number", "Enter here"));
    var c = 5;
    var message = "Guess its square now in 5 tries";
    (function receiveAnswer() {
        var input2 = parseInt(window.prompt(message));
        if (input2 == input * input) {
            alert("Good!");
        } else {
            c--;
            if (c === 0) {
                alert("Ran out of attempts!");
            } else {
                message = "Wrong, enter again! " + c + " attempts left!";
                receiveAnswer();
            }
        }
    })();
}

您缺少关闭括号:

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries")); //<--- here
if (input2 == input*input) {
  alert("Good!");
} else {
  prompt("Wrong, enter again!");
}

...您需要一个循环。最简单的理解是for

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));
for (var i = 0; i < 5; i++) {
  if (input2 == input*input) {
    alert("Good!");
    i = 5;
  } else {
    input2 = prompt("Wrong, enter again!")
  }
}
    

使用 do-while

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));
var tries = 1;
do {
  if (input2 == input * input) {
    alert("Good!");
    break;
  } else {
    prompt("Wrong, enter again!");
  }
} while (++tries < 5);

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));
var tries = 0;
do {
  if (input2 == input * input) {
    alert("Good!");
    break;
  } else {
    input2 = parseInt(window.prompt("Wrong, enter again!"));
  }
} while (++tries < 5);

最新更新