我正在做一个猜谜游戏。如何强制用户在提示框中输入数字?

var secretNumber = 4
var guess = Number(prompt("Guess a Number"));
if (guess === secretNumber) {
    alert("you got it right brah!!!!!!");
}
if (NaN(guess)) {
    alert("must input numbers")
    return false;
}
else if (guess < secretNumber) {
    alert("your number is too low !");
}
else {
    alert("your number is too high !");
}





if (NaN(guess)) {
    alert("must input numbers")
    return false;


我希望当用户填写字母或任何非数字的内容时会收到警报,告知他必须使用数字。

最佳答案

您可以使用do-while循环不断提示用户,直到他们输入数字为止:



let inp;
do {
  inp = +prompt("Guess a number");
} while(isNaN(inp));

// --- Perform logic with `inp` as a number ---
// You can now assume inp here is a number
console.log(inp + 1);

关于javascript - 强制用户在提示中仅插入数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58350302/

10-11 14:09