0

我对这段代码有疑问:

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,从而满足这两个条件。

我难住了。我想底线是如何有效地将字符串从提示匹配到数组,测试每个项目以及如果提示字符串不存在如何解析数组。

4

6 回答 6

2

在第一次迭代中,输入的水果要么是要么不等于“苹果”。但是,如果第一次迭代不是“apple”(但例如“orange”),那么这并不意味着“orange”根本不可用。

您应该跟踪您是否匹配了任何东西(通过使用变量),并且只有在循环之后没有匹配任何内容时,输入的水果确实不可用。

于 2012-10-28T15:21:02.307 回答
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);
}
于 2012-10-28T15:23:36.783 回答
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.");
}

希望这可以帮助 :)

于 2012-10-28T15:26:39.037 回答
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)
}
于 2012-10-28T15:33:26.543 回答
0

将 items[i] 更改为 fruits[i] 这将解决您的问题

于 2012-10-28T15:26:16.517 回答
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.");
}
于 2012-10-28T15:57:32.210 回答