我对此代码有疑问:

var buyerChoice = prompt("Enter a either apple, orange, or banana:", "");

var fruits = new Array ("apple", "orange", "banana");

for(i=0; i < fruits.length; i++) {
    if(buyerChoice === fruits[i]) {
        document.write(buyerChoice);
    } else if (buyerChoice !== fruits[i]){
        document.write("Sorry, " +buyerChoice+ " is out of season.");
        break;
    }
}


我认为问题出在else-if语句中,因为每次我键入变量中存在的项目时,它都会返回//appleSorry, apple is out of season,从而满足这两个条件。

我很困惑我猜想最重要的是如何有效地将提示中的字符串匹配到数组,测试每个项目以及如果提示字符串不存在则如何解析数组。

最佳答案

var buyerChoice = prompt("Enter a either apple, orange, or banana:", "");

var fruits = ["apple", "orange", "banana"];

var outOfSeason = false;
for(fruit in fruits) {
    if(buyerChoice === fruits[fruit]) {
        matched = true;
        break;
    }
}

if(! outOfSeason){
   document.write(buyerChoice);
}
else{
   document.write("Sorry, " +buyerChoice+ " is out of season.");
}

09-16 20:39