[英]How to prompt until condition is met?
我試圖提示用戶,直到輸入等於數組中的元素之一?
do {
var bestCities = ["miami","sanfrancisco","austin","chicago","phoenix"]
var userInput = prompt('Whats your city?');
} while (
userInput !== bestCities[i]
);
alert('I love ' + i + ' also' );
可能:
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
位置。
這是一個更好的架構:
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' );
只需檢查數組索引即可解決問題
一個更好的方法:
const bestCities = ["miami", "sanfrancisco", "austin", "chicago", "phoenix"];
let userInput;
do {
userInput = prompt("Whats your city?");
} while (!bestCities.includes(userInput));
alert(`I love ${userInput} also`);
注意:這只是對當前最熱門答案的改進。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.