2016-08-25 9 views
0

javascriptプロンプトの戻り値の型は常にオブジェクトですか?

function check_color(){ 
 
\t 
 
\t color_input = prompt("I am thinking of one of these colors: \n\n"+ 
 
\t \t \t \t \t \t "blue, cyan, gold, gray, magenta, orange, red, white, yellow \n\n"+ 
 
\t \t \t \t \t \t "What color am I thinking of?"); 
 
\t 
 
\t if(color_input != null || color_input != undefined){ 
 
\t 
 
\t \t if(typeof (color_input) != 'string') { 
 
\t \t \t alert("This is not any color. \n\n"+ 
 
\t \t \t "Please enter color in text format"); 
 
\t \t \t return false; 
 
\t } 
 
\t 
 
\t \t if(colors.indexOf(color_input) < 0){ 
 
\t \t \t alert("Sorry, i don't recognize your color. \n\n"+ 
 
\t \t \t "Please try again"); 
 
\t \t \t return false; 
 
\t } 
 
    } 
 
    else{ 
 
\t alert("Please enter some input"); 
 
\t return false; 
 
    } 
 
}

なぜ常に最初-場合は、このコードを実行しようとすると、ブロックが実行されていますか?誰かがexpalinしてくださいできますか?

+0

これはOR条件の仕組みです。 'color_input!= null || color_input!= undefined'は 'color_input!= null && color_input!= undefined'です。 – Tushar

+0

@Tusharそれは条件ではありませんか?もし私が狂気ならCorect ng。 – izengod

+0

&& = and、|| =または –

答えて

0

私はこの問題を確認していないが、期待通りjsFiddleにこのコードスニペットは動作します:

function check_color() { 
    color_input = prompt("I am thinking of one of these colors: \n\n" + 
     "blue, cyan, gold, gray, magenta, orange, red, white, yellow \n\n" + 
     "What color am I thinking of?"); 

    colors = ["blue", "cyan", "gold", "gray", "magenta", "orange", "red", "white", "yellow"]; 

    if (color_input != null) { 

    if (typeof(color_input) != 'string') { 
     console.log("This is not any color. \n\n" + 
      "Please enter color in text format"); 
     return false; 
    } 

    if (colors.indexOf(color_input) < 0) { 
     console.log("Sorry, i don't recognize your color. \n\n" + 
      "Please try again"); 
     return false; 
    } 

    console.log("your color:" + color_input); 
    } else { 
    console.log("Please enter some input"); 
    return false; 
    } 
} 
check_color(); 

私はスニペットに色の配列を追加する必要がありました(私はあなたが他の場所でそれを持っていたと仮定しています)。また、プロンプトが文字列またはnullのみを返すので、 "|| undefined"を取り出しました。そのための

、次のようなコードを簡素化することができます:私はここのコンソールエラーを取得しています(colors.indexOf(color_input)

場合

function check_color() { 
    color_input = prompt("I am thinking of one of these colors: \n\n" + 
     "blue, cyan, gold, gray, magenta, orange, red, white, yellow \n\n" + 
     "What color am I thinking of?"); 

    colors = ["blue", "cyan", "gold", "gray", "magenta", "orange", "red",  "white", "yellow"]; 

    if (color_input) { // null would be false 
     if (colors.indexOf(color_input) < 0) { 
     console.log("Sorry, i don't recognize your color. \n\n" + 
      "Please try again"); 
     return false; 
     } 

     console.log("your color:" + color_input); 
    } else { 
     console.log("Please enter some input"); 
     return false; 
    } 
} 
check_color(); 
+0

多くの情報をありがとう。プロンプトは文字列またはnullを返すだけなので、nullでない場合はcolor_inputが文字列型かどうかを確認する必要はありません。 – izengod

1

はここで、 "色" ある 。色の配列を追加してください