2016-04-10 8 views
-2

私の関数を呼び出すと、構文エラーが発生します。それ以外はすべてそれ自身で動作します。エラーはスローされます。このjavascript関数呼び出しが機能しないのはなぜですか?

console.log(compare(userChoice, computerChoice)); 

エラーは次のとおりです。

SyntaxError: Unexpected token {

任意のアイデア?

var userChoice = prompt("Do you choose rock, paper or scissors?"); 
 
var computerChoice = Math.random(); 
 

 
if (computerChoice < 0.34) 
 
{ 
 
\t computerChoice = "rock"; 
 
} 
 
else if(computerChoice <= 0.67) 
 
{ 
 
\t computerChoice = "paper"; 
 
} 
 
else 
 
{ 
 
\t computerChoice = "scissors"; 
 
} 
 

 

 
var compare = function(choice1, choice2) 
 
{ 
 
    if (choice1 === choice2) 
 
    { 
 
     return "The result is a tie!"; 
 
    } 
 
    else if (choice1 === "rock") 
 
    { 
 
     if (choice2 === "scissors") 
 
     { 
 
      return "rock wins"; 
 
     } 
 
     else 
 
     { 
 
      return "paper wins"; 
 
     } 
 
    } 
 
    else if (choice1 === "paper") 
 
    { 
 
     
 
     if (choice2 === "rock") 
 
     { 
 
      return "paper wins" 
 
     } 
 
     else 
 
     { 
 
      return "scissors wins" 
 
     } 
 
     
 
    } 
 
    else if (choice1 === "scissors") 
 
    { 
 
     if (choice2 === "paper" 
 
     { 
 
      return "paper wins" 
 
     } 
 
     else 
 
     { 
 
      return "scissors wins" 
 
     } 
 
    } 
 
} 
 

 
console.log(compare(userChoice, computerChoice));

+0

'if(choice2 ===" paper "' - '' if '条件式の後に ''がありません) – Pointy

+0

Ooooppssがエラーを追加しましたthanks man –

+0

あなたの個人用デバッガではありません。 – Oriol

答えて

1

はい、あなたはif (choice2 === "paper")を忘れてしまいました。

0

他の人が指摘しているように、あなたのクローズ)が見つかりませんでした。

ネストされたif - elseブロックがたくさんある場合、(){}のトラッキングが簡単に失われます。あなたはずっと、短いよりよい、あなたは他の条件文や表現、すなわちswitch声明と?オペレータを活用場合は、コードを読みやすく書くことができます。

function compare(choice1, choice2) { 
    if (choice1 === choice2) { 
     return 'The result is a tie'; 
    } 

    switch(choice1) { 
     case 'rock': 
      return choice2 === 'scissors' ? 'rock wins' : 'paper wins'; 
     case 'paper': 
      return choice2 === 'rock' ? 'paper wins' : 'scissors win'; 
     case 'scissors': 
      return choice2 === 'paper' ? 'scissors win' : 'rock wins'; 
    } 
} 

あなたが見ることができるように、このコードは非常に少ない()秒を持っているとし、 {}s。

関連する問題