var userChoice = prompt("What would you like to play?"),
computerChoice = Math.random();
if (computerChoice <= 0.34){
computerChoice = "Rock";
}
else if (computerChoice >= 0.35 && computerChoice <= 0.67){
computerChoice = "Paper";
}
else {
computerChoice = "Scissors";
}
document.write("Computer's choice is " + computerChoice);
var compare = function(choice1, choice2) {
if (choice1 === choice2){
return "This 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 === "Rock"){
return "Rock WINS";
}
else {
return "Scissors wins";
}
}
};
document.write(compare(userChoice, computerChoice));
<!doctype html>
<html>
<title>JS Practice</title>
<head>
<script language="javascript">
</script>
</head>
<body>
</body>
</html>
请帮助我理解为什么它不显示返回的字符串?当你赢或输的时候应该显示结果。我从codeacademy获得了这段代码。在他们的控制台上运行完美,但是当你尝试在浏览器上运行它时,它无法正常工作。困惑......
var userChoice = prompt("What would you like to play?");
var computerChoice = Math.random();
if (computerChoice <= 0.34){
computerChoice = "Rock";
}
else if (computerChoice >= 0.35 && computerChoice <= 0.67){
computerChoice = "Paper";
}
else {
computerChoice = "Scissors";
}
document.write("Computer's choice is " + computerChoice);
var compare = function(choice1, choice2){
if (choice1 === choice2){
return "This 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 === "Rock"){
return "Rock WINS";
}
else {
return "Scissors wins";
}
}
};
compare(userChoice, computerChoice);
答案 0 :(得分:0)
代码正确且工作正常,您只是忘记了展示它的重要部分。
您没有将结果写入实际文档。你调用该函数并正确返回,但你没有明显地显示答案。试试这段代码:
var userChoice = prompt("What would you like to play?"),
computerChoice = Math.random();
if (computerChoice <= 0.34){
computerChoice = "Rock";
}
else if (computerChoice >= 0.35 && computerChoice <= 0.67){
computerChoice = "Paper";
}
else {
computerChoice = "Scissors";
}
document.write("Computer's choice is " + computerChoice);
var compare = function(choice1, choice2) {
if (choice1 === choice2){
return "This 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 === "Rock"){
return "Rock WINS";
}
else {
return "Scissors wins";
}
}
else {
return "Invalid input! Type either rock, paper, or scissors!"
}
};
document.write(", " + compare(userChoice, computerChoice));
&#13;
您错过了最后一个document.write将结果写入文档。你可以自己格式化。如果输入有效,我还建议添加另一个案例。如果输入有效,您也可以将主提示放在函数中并调用递归。