验证和循环javascript [英] validating and looping javascript

查看:58
本文介绍了验证和循环javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证三种不同提示的用户输出,并认为这会起作用,但事实并非如此.

I need to validate the user output for three different prompts and thought this would work but it is not.

第一个提示需要验证澳大利亚的8个州和地区中的任何一个.

The first prompt need to validate any of the 8 states and territories of Australia.

第二个提示需要验证用户是否输入了整数.

The second prompt needs to validate that the user has entered a whole number.

第三个提示需要验证用户是否输入了可以为整数或小数的负数或正数.

The third prompt needs to validate that the user has entered a negative or positive number that can be whole or has decimals.

然后整个过程需要再次循环,因此可以再次询问三个提示.这样就可以建立表格了.

Then the whole thing needs to loop over again so the three prompts can be asked again. So it can build a table.

        function ask() {
          var stInput = '';
          var populationInput = '';
          var changeInput = '';

          var entering = confirm('Confirm to add state or territory');
          if (!entering) {
            return;
            } else {
              while (true) {
                stInput = prompt('Enter state or territory');
                    function validateUserChoice(stInput) {
                if (stInput !== "Queensland" && stInput !== "New South Wales" && stInput !== "Victoria" && stInput !== "Tasmania" && stInput !== "Northern Territory" && stInput !== "Western Australia" && stInput !== "South Australia" && stInput !== "Australian Capital Territory") {

                   } else {
                    return false;
                   }
               }
                populationInput = prompt('Enter population for ' + stInput + '');

                while(!isValid(populationInput)) {
                alert('Your input was invalid');
                populationInput = parseInt(prompt('Enter population for ' + stInput + ''));
                }
                changeInput = prompt('Enter growth rate for ' + populationInput + '');

                while(!isValid(changeInput)) {
                alert('Your input was invalid');
                changeInput = parseFloat(prompt('Enter growth rate for ' + populationInput + ''));
                }
                    break;
                }
                 alert("invalid state or territory"); 
                }

推荐答案

我无法说出您更大的问题,但是我会告诉您,每当我使用while循环时,我总是以故障保护方式进行编程.我通常称它们为safetyValve.它可以防止系统陷入无限循环和崩溃.看起来有点像:

I cannot speak to your larger problem, but I will tell you, any time I use a while loop, I always program in a fail safe. I usually call them a safetyValve. It keeps the system from being caught in an infinite loop and crashing. It looks a little like:

var myCondition = true;
var safetyValve = 0;
var safetyMax = 10000;
while (myCondition && safetyValve < safetyMax) {
  ...
  safetyValve++;
}

这篇关于验证和循环javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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