简体   繁体   English

如何提示直到条件满足?

[英]How to prompt until condition is met?

Im trying to prompt the user until the input is equal to one of the elements in the array?我试图提示用户,直到输入等于数组中的元素之一?

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

Could be: 可能:

 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() returns the position from an array. indexOf()返回数组的位置。

indexOf returns -1 when no matches were found. 未找到匹配项时, indexOf返回-1 So the loop ends when it finds an index other than -1 . 因此,当找到-1以外的索引时,循环结束。 For example miami is in the 0 position and chicago in the 3 position. 例如, miami处于0位置, chicago处于3位置。

Here's a better architecture: 这是一个更好的架构:

var validCity = false;

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

Just a check in array index will do the trick 只需检查数组索引即可解决问题

An even better way to do it:一个更好的方法:

const bestCities = ["miami", "sanfrancisco", "austin", "chicago", "phoenix"];
let userInput;
do {
  userInput = prompt("Whats your city?");
} while (!bestCities.includes(userInput));
alert(`I love ${userInput} also`);

Note: This is just an improvement to the current most top answer.注意:这只是对当前最热门答案的改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM