我试图提示用户,直到输入等于数组中的一个元素?
do {
var bestCities = ["miami","sanfrancisco","austin","chicago","phoenix"]
var userInput = prompt('Whats your city?');
} while (
userInput !== bestCities[i]
);
alert('I love ' + i + ' also' );
答案 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' );
只需检查数组索引就可以了解