2015-10-08 58 views
0

計算機繼續提醒我「 糟糕,請再試一次。您的代碼返回'rock win!'而不是「未定義」當輸入剪刀和紙」,即使代碼工作JavaScript中的岩石,紙張,剪刀13

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){ 
    choice1=userChoice; 
    choice2=computerChoice; 
    if (choice1===choice2){ 
     return"The result is a tie!"; 
    } else if(choice1==="rock"){ 
     if (choice2==="scissors"){ 
      return"rock win!"; 
     } else { 
      return"paper win!!"; 
     } 
    } else if (choice1==="scissors"){ 
     if(choice2==="rock"){ 
      return"rock wins!"; 
     } else { 
      return"scissors wins"; 
     } 
    } else { 
     if(choice2==="rock"){ 
      return"paper wins"; 
     } else { 
      return"scissors wins"; 
     } 
    } 
}; 
+0

爲什麼java的標籤? –

+0

它應該是'if(computerChoice <0.34)computerChoice =「rock」;其他if(computerChoice> = 0.34 && computerChoice <= 0.67)computerChoice =「paper」; } else { computerChoice =「scissors」; }' –

+0

抱歉,我仍然是初學者,所以我不知道有什麼區別。 – mody

回答

0

至於我可以看到代碼工作,如果你正確地調用比較功能,實際上它傳遞userChoice和computerChoice作爲參數:

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"; 
 
} 
 

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

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