JavaScript-输入非数字时提示 [英] JavaScript - Prompt while input is not a number

查看:72
本文介绍了JavaScript-输入非数字时提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问用户一个数字,而他的答案不是一个数字,问题将不断循环(作为警报框).

I want to ask the user for a number, while his answer is not a number the question will keep on looping (as an alert box).

我试图通过while循环和 isNaN 来做到这一点,但是我做错了事.

I tried to do that with while loop and isNaN, but i'm doing something wrong.

这是我的Js:

var correct = false;

do {
    var question = prompt("guess the number?");
    if (question !== isNaN) {
        document.write("your number is " + question);
        correct = true;
        break;
   }

} while(! correct);

推荐答案

我将通过以下示例为您提供一些提示:

I will give you some tips with the following sample:

<html>
 <head>
    <title></title>
    <script>

    var answer = "";

    do {
        answer = prompt("guess the number?");
    } while(!isNumber(answer));

    document.write("your number is " + answer);

    function isNumber(value) {
      var numberPattern = /^[0-9]+$/; // one or more of digits 0 to 9
      return numberPattern.test(value);
    }

    </script>
 </head>
 <body>

</body>

此处的示例: https://plnkr.co/edit/ziysG36if9OTZahHfSbO

  • 由于您拥有明确的条件isNan(answer),因此不必创建一个称为correct的附加变量来检查条件是否为true,因此while应该使用该条件"while(isNan(答案)).

  • It is not necessary to create an additional variable called correct to check if the condition is true or false because you have the condition clear, isNan(answer), so the while should use that condition "while (isNan(answer))".

在编写代码时,应尽可能简洁地编写代码,并且如果要保存提示结果,则更清楚地将变量命名为"answer",因为要保存的是答案而不是问题,即方法调用.

When you write code you should write as clean as possible and if you are saving the result of prompt it is more clear to name the variable "answer" because you are saving the answer and not the question, which is a method call.

这篇关于JavaScript-输入非数字时提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆