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

最初の反復では、入力された果物は「りんご」と等しいか、等しくないかのいずれかです。ただし、最初の繰り返しが「リンゴ」ではない場合 (ただし、「オレンジ」など)、「オレンジ」がまったく利用できないという意味ではありません。

(変数を使用して) 何かに一致したかどうかを追跡する必要があり、ループ後に何も一致しなかった場合にのみ、入力された果物は実際には利用できません。

于 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

forループが何を達成しようとしているのか100%確信が持てませんが、使用できます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
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 に答える
0

アイテム[i]を果物[i]に変更すると、問題が解決します

于 2012-10-28T15:26:16.517 に答える