2017-02-21 107 views
1

我不知道錯誤在哪裏了。它首先說我有一個意外的標識符,然後我有一個無與倫比的},現在我有一個非法的返回聲明。我只需要一些幫助。謝謝。我不知道錯誤在哪裏

var userChoice = prompt("Do you choose rock, paper or scissors?"); 
var computerChoice = Math.random(); 
if (computerChoice < 0.34) { 
    computerChoice = "rock"; 
} else if (computerChoice <= 0.67) { 
computerChoice = "paper"; 
} else { 
    computerChoice = "scissors"; 
} 
console.log("Computer: " + computerChoice); 
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"; 
     } 
     if (choice2 === "rock") { 
      return "paper wins"; 
     } else { 
      return "scissors wins"; 
     } else if (choice1 === "paper") { 
      if (choice2 === "rock") { 
       return "paper wins"; 
      } else { 
       return "scissors wins"; 
      } 
     } 
+0

你錯過了一個大括號 – geeves

+0

它是否可以將computerChoice設置爲數字然後作爲一個字符串呢?只是好奇,我可能會有2個變量,每個類型一個。 – Forklift

+1

31行有一個「else if」跟在「else」之後,那個「Else If」永遠不會到達。 在JavaScript中,一個變量可以是一個數字,然後是一個字符串。 – geeves

回答

1
var userChoice = prompt("Do you choose rock, paper or scissors?"); 
var computerChoice = Math.random(); 
if (computerChoice < 0.34) { 
    computerChoice = "rock"; 
} else if (computerChoice <= 0.67) { 
    computerChoice = "paper"; 
} else { 
    computerChoice = "scissors"; 
} 
console.log("Computer: " + computerChoice); 
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"; 
     } 
     if (choice2 === "rock") { 
      return "paper wins"; 
     } else if (choice1 === "paper") { 
      if (choice2 === "rock") { 
       return "paper wins"; 
      } else { 
       return "scissors wins"; 
      } 
     } 
    } 
} 

正確縮進代碼可以幫助尋找失蹤的花括號。當某些東西縮進4次時,是時候看看它是否可以重構。

例如:

第一如果有一個返回。在那之後沒有理由有一個「別的如果」。這將擺脫一個縮進。同樣可以這樣說(「choice2 ===」rock「)。相信當回報被寫入時,它實際上會返回。

+0

由於這看起來像是codewars.com問題或其他問題,我認爲最好是重構一下而不是接收重構代碼。 :)祝你好運,你會得到它。 – geeves

+1

Upvoted在代碼示例下提供了很好的建議。 – Forklift

+1

geeves,謝謝你的建議和幫助!它真的幫助我,讓我看到我的錯誤。謝謝。向上投票反饋和解釋。 –

相關問題