2016-09-04 9 views
1

ユーザの入力が配列の要素と一致しない場合、配列の各要素をユーザ入力と比較してメッセージを生成しようとしています。私が使用するコードは以下の通りです。変数を配列の要素と比較する(Javaスクリプト)

var guess_input; 
var finished = false; 
var colors = ["Aqua", "BurlyWood", "Cornsilk", "DarkGrey", "DarkRed", "Indigo", "LightGrey"]; 

while (!finished) { 
      guess_input = prompt("I'm thinking of one of these colors:\n\n" + "Aqua, BurlyWood, Cornsilk, DarkGrey, DarkRed, Indigo, LightGrey" + "\n\nWhat is the color I'm thinking of?"); 
      finished = check_guess(); 
      } 
     } 
     function check_guess() { 

     if (guess_input != colors[0] || guess_input != colors[1] || guess_input != colors[2] || guess_input != colors[3]) { 
      alert("Sorry, I don't recognize that color!\n\n" + "Please try again."); 
      return false; 
     } 
} 

このコードの問題は、配列から1つの要素だけを選択すると完全に正常に動作することです。しかし、私は 'OR'演算子を使用すると、動作しません。これを行うための良い方法はありますか?私はJavaスクリプトで新しいです。

ありがとうございます!

+0

なぜあなたのループ内で関数を宣言していますか?外に宣言すると、毎回関数の作成を繰り返しません。 –

+0

array.prototype.find()を使用するとより効率的になります –

+0

@Jonasw、これは、すべてのelemebtがチェックする必要がある場合にのみ機能しますが、 、要素0 ... 2のように。 –

答えて

1

すべての色を確認する必要があるため、logical ANDオペレータ&&を使用できます。作業コードについては

if (guess_input != colors[0] && guess_input != colors[1] && guess_input != colors[2] && guess_input != colors[3]) { 
    alert("Sorry, I don't recognize that color!\n\n" + "Please try again."); 
    return false; 
} 

、あなたにも、見つかった色のtrueを返却する必要があります。

var guess_input; 
 
var finished = false; 
 
var colors = ["Aqua", "BurlyWood", "Cornsilk", "DarkGrey", "DarkRed", "Indigo", "LightGrey"]; 
 

 
while (!finished) { 
 
    guess_input = prompt("I'm thinking of one of these colors:\n\n" + "Aqua, BurlyWood, Cornsilk, DarkGrey, DarkRed, Indigo, LightGrey" + "\n\nWhat is the color I'm thinking of?"); 
 
    finished = check_guess(); 
 
} 
 

 
function check_guess() { 
 
    if (guess_input != colors[0] && guess_input != colors[1] && guess_input != colors[2] && guess_input != colors[3]) { 
 
     alert("Sorry, I don't recognize that color!\n\n" + "Please try again."); 
 
     return false; 
 
    } 
 
    return true; // necessary, otherwise the function returns undefined, which is a falsy value 
 
}

0

あなたはcolours配列内の項目に対してguess_inputを比較する必要があります。これは、で定義された条件に応じて、メソッドでは完璧な仕事で、trueまたはfalseを返します。たとえば...ここ

var test_guess = colours.some(function(color) { 
    /* 'color' = each item in 'colours' */ 
    return color === guess_input; 
}); 

if (test_guess) { 
    /* correct ..... */ 
} else { 
    /* incorrect .... */ 
} 

.some()は、条件がtrueを返すまでcolours、アレイ内のすべての項目を反復処理を開始します。変数test_guessは、推定値が色と一致する場合はtrue、そうでない場合はfalseになります。

参照:Array.prototype.some() @ MDN

関連する問題