Javascript:创建循环来检查变量是否为 int

标签 javascript loops typeof

我有一个提示问题的变量。我想确保对方回答的是数字而不是“五”。但也要发出警告消息,表明该号码无效,并再次询问问题。我还是个新手,相信我做错了。这是我到目前为止所拥有的。

var question = prompt("Enter a number");
for(i=0; i = question; i++){
    if{
        typeof question != "number");
        console.log("question not number");
        alert("Please try again");
}

最佳答案

您可以创建一个提出问题的函数。如果答案不满足您,您可以再次调用该函数本身。

var askQuestion = function() {
    var response = prompt("Enter a number");

    // if it is good, return true (insert your condition in the if)
    if(true) {
        return true;
    }
    // If it is not good, recall the function, so it recall the question
    else {
        return askQuestion();
    }
}

然后在您的代码中执行如下操作:

if(askQuestion()) {
    // The person answered what you want
} 
// There is no else because it prompt the question all the time 
// if the answer is not what you are excepting

关于Javascript:创建循环来检查变量是否为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35344949/

相关文章:

javascript - JQuery 数据表文本框列悬停

java - 打印输入正整数的公约数

c - 链接列表向后显示

javascript - 每当在网格中单击一行时调用 array.splice() 是否明智

javascript - 有没有一种好方法可以在 HTML 或 JavaScript 中向用户显示收集的数据并仍然保留数据?

javascript - onClick跳转到页面顶部

javascript - 如何将一个数组的值设置为另一个数组?

JavaScript短路评估错误?

javascript - 在我的应用程序中使用 webpack 并且不能使用 javascript 的 typeof 指令

JavaScript:检测参数是否是数组而不是对象(Node.JS)