我是js的新手,我刚刚根据摇滚,纸张,剪刀游戏编写了下面的基本功能。由于某种原因,比较功能的结果始终显示为a “画”而不是其他结果。我在这里做错了什么?
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";
}
choice1 = userChoice;
choice2 = computerChoice;
var compare = function (choice1, choice2) {
if (choice1 == choice2) {
return "draw!";
}
if (choice1 == "rock") {
if (choice2 == "scissors") {
return "rock wins!";
} else {
return "paper wins!";
}
}
if (choice1 == "paper") {
if (choice2 == "scissors") {
return "scissors wins!";
} else {
return "paper wins!";
}
}
if (choice1 == "scissors") {
if (choice2 == "rock") {
return "rock wins!";
} else {
return "scissors wins!";
}
}
};
compare();
谢谢,我们
答案 0 :(得分:4)
您正在调用不带参数的比较:
compare();
因此choice1
和choice2
都等于undefined
,你的游戏总是以平局结束。
您应该尝试像这样调用比较函数:
compare(userChoice, computerChoice);
如果定义了一个函数,则参数列表定义函数范围内给定变量的名称。它不是函数本身应该可用的变量的命名约定。
答案 1 :(得分:0)
您已使用两个参数定义了该函数:
var compare = function (choice1, choice2)
但是你用0调用它。
尝试指定选项:
compare("rock", "paper");
答案 2 :(得分:0)
只能通过键入不带参数的func_name()来打开函数,就像“干镜头”一样。阅读function declaring
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";
}
choice1 = userChoice;
choice2 = computerChoice;
function compare (choice1, choice2) {
if (choice1 == choice2) {
return "draw!";
};
if (choice1 == "rock") {
if (choice2 == "scissors") {
return "rock wins!";
} else {
return "paper wins!";
}
}
if (choice1 == "paper") {
if (choice2 == "scissors") {
return "scissors wins!";
} else {
return "paper wins!";
}
}
if (choice1 == "scissors") {
if (choice2 == "rock") {
return "rock wins!";
} else {
return "scissors wins!";
}
}
};
compare(choice1, choice2);