如何提示直到满足条件?

时间:2015-07-03 04:47:00

标签: javascript loops prompt

我试图提示用户,直到输入等于数组中的一个元素?

do {
      var bestCities = ["miami","sanfrancisco","austin","chicago","phoenix"]
      var userInput = prompt('Whats your city?');
    } while (
        userInput !== bestCities[i]
      );
    alert('I love ' + i + ' also' );

3 个答案:

答案 0 :(得分:1)

可能是:

var bestCities = ["miami","sanfrancisco","austin","chicago","phoenix"];
var userInput;

do{
  userInput = prompt('Whats your city?') 
} while (bestCities.indexOf(userInput) === -1);

alert('I love ' + userInput + ' also' )

  

indexOf() 从数组中返回位置。

如果未找到匹配项,则

indexOf会返回-1。因此,当循环找到除-1之外的索引时,循环结束。例如,miami位于0位置,chicago位于3位置。

答案 1 :(得分:0)

这是一个更好的架构:

var validCity = false;

while(!validCity) {
    var input = prompt("What is your city");
    if(bestCities.indexOf(input) != -1) validCity = true;
}

答案 2 :(得分:0)

do {
      var bestCities = ["miami","sanfrancisco","austin","chicago","phoenix"]
      var userInput = prompt('Whats your city?');
    } 
while (bestCities.indexOf(userInput)==-1);
alert('I love ' + userInput  + ' also' );

只需检查数组索引就可以了解