我对此代码有疑问:
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
,从而满足这两个条件。
我很难过。我想底线是如何有效地匹配从提示符到数组的字符串,测试每个项目以及如果提示字符串不存在,如何解析数组。
答案 0 :(得分:2)
在第一次迭代中,输入的水果要么等于或不等于“apple”。但如果它不是第一次迭代的“苹果”(但例如“橙色”),那么这并不意味着“橙色”根本不可用。
你应该跟踪你是否匹配任何东西(通过使用变量),并且只有当循环之后没有匹配时,输入的水果确实不可用。
答案 1 :(得分:1)
你的for循环根本不符合逻辑。因此items
如果未定义则不会工作。
这是一个可能的解决方案
var outofseason = true;
for(i=0; i < fruits.length; i++) {
if(buyerChoice === fruits[i]) {
outofseason = false;
break;
}
}
if ( outofseason ) {
document.write("Sorry, " +buyerChoice+ " is out of season.");
}
else {
document.write(buyerChoice);
}
答案 2 :(得分:1)
// let the fruits be a global var instead of recreating it every time you call the function below
var fruits = ["apple", "orange", "banana"];
function askBuyerForFruit() {
var buyerChoice = prompt("Enter a either apple, orange, or banana:", "");
for (var i = 0; i < fruits.length; i++) {
if (fruits[i] === buyerChoice) {
document.write(buyerChoice);
// get out of the function if found;
return;
}
}
// fallback if no matching fruit found
document.write("Sorry, " +buyerChoice+ " is out of season.");
}
希望这会有所帮助:)
答案 3 :(得分:1)
不是100%确定for循环尝试完成的内容,但您可以使用indexOf
var buyerChoice = prompt("Enter a either apple, orange, or banana:", "");
var fruits = new Array ("apple", "orange", "banana");
var matchedIndex = fruits.indexOf(buyerChoice);
if (matchedIndex < 0) { //did not match
document.write("Sorry, " +buyerChoice+ " is out of season.");
} else {
document.write(buyerChoice)
}
答案 4 :(得分:0)
将项目[i]更改为fruit [i]这将解决您的问题
答案 5 :(得分:0)
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.");
}