Javascript Prompt Validation?

2019-03-04 07:16发布

问题:

I want to prompt the user to enter a sport (baseball, football, soccer, or track). Let's say I enter "Golf". How do I get it to keep asking me to enter a sport until I enter one of the valid sports? The sport determines what field they play on. Below is my code.

var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase (); 

switch (sport) {
    case "baseball": 
        field = "Field 1";
        break;
    case "football": 
        field = "Field 2";
        break;
    case "soccer":
        field = "Field 3";
        break;
    case "track":
        field = "Field 4";
        break;
    default: alert("Please enter a valid sport");
}

回答1:

loop:
while(true){
    var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase(); 
    switch (sport) {
        case "baseball": 
            field = "Field 1";
            break loop;
        case "football": 
            field = "Field 2";
            break loop;
        case "soccer":
            field = "Field 3";
            break loop;
        case "track":
            field = "Field 4";
            break loop;
        default: alert("Please enter a valid sport");
    }
}

or

var field;
while(true){
    var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase();
    if(!sport || /^(baseball|football|soccer|track)$/.test(sport)){
        field = "Field " + ("baseball|football|soccer|track".split("|").indexOf(sport)+1);
        break;
    }else{
        alert("Please enter a valid sport");
    }
}