validating and looping javascript

好久不见. 提交于 2019-12-08 08:30:09

问题


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

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

回答1:


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++;
}


来源:https://stackoverflow.com/questions/55822359/validating-and-looping-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!