【问题标题】:Javascript: Creating loop to check variable if its an intJavascript:创建循环以检查变量是否为 int
【发布时间】:2016-02-11 16:36:36
【问题描述】:

我有一个提示问题的变量。我想确保这个人用数字而不是“五”来回答。但也给出一个警告信息,它不是一个有效的号码,并再次问这个问题。我还是新手,相信我做错了。这是我目前所拥有的。

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");
}

【问题讨论】:

  • 您的 if 使用的是开放的 { 而不是 (,并且有一个分号,而不是使用 {}'s
  • 你想达到什么目的,首先你有一个语法错误,其次这将导致循环无限执行。

标签: javascript loops typeof


【解决方案1】:

您可以创建一个用于提问的函数。如果答案不满足您的要求,您可以从自身再次调用此函数。

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

【讨论】:

    【解决方案2】:

    你可以用parseInt()检查一个值是否是数字,然后用isNaN()实际检查它是否是一个数字。这将起作用:

    var question = prompt("Enter a number");
    if (isNaN(parseInt(question))) {
        console.log("question not number");
        alert("Please try again");
    }
    

    【讨论】:

      【解决方案3】:

      一种循环方式,直到输入为整数:

      var question;
      while (isNaN(parseInt(question = prompt("Enter a number"))))
      {
         console.log("Question is not a number");
         alert("Please try again");
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用isNaN() 来检查用户输入的是否不是数字。这意味着您可以使用 !isNaN() 检查用户输入是否为数字。

        function isValidAns(ans){
            if(isNaN(ans)) return false;
            if(ans == 5) return false;
        
            return true;
        }
        

        您可能还需要一个 while 循环来让用户一次又一次地输入,直到输入有效为止。

        var ans = "";
        while(true){
            ans = prompt("Enter a number");
            if(isValidAns(ans)){
                break;
            }else{
                alert("Please try again.")
            }
        }
        

        【讨论】:

        • 请为您的解决方案添加一些解释。
        猜你喜欢
        • 2021-08-11
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-27
        • 1970-01-01
        相关资源
        最近更新 更多