Javascript控制台未打印调用的函数
我刚开始学习JavaScript,我正在努力改进我构建的“石头、剪刀、纸”游戏(见下面的代码) 我尝试在没有最后一个函数input()的情况下构建游戏。但我知道我只能在函数中使用“return”。当我使用console.log()打印函数时,它在没有input()函数的情况下工作 我想学习如何使用input()函数实现这一点,以及如何在input()中调用gamePlay()。任何帮助都将不胜感激Javascript控制台未打印调用的函数,javascript,Javascript,我刚开始学习JavaScript,我正在努力改进我构建的“石头、剪刀、纸”游戏(见下面的代码) 我尝试在没有最后一个函数input()的情况下构建游戏。但我知道我只能在函数中使用“return”。当我使用console.log()打印函数时,它在没有input()函数的情况下工作 我想学习如何使用input()函数实现这一点,以及如何在input()中调用gamePlay()。任何帮助都将不胜感激 var gamePlay = function (userGameChoice) { va
var gamePlay = function (userGameChoice) {
var computerChoice = Math.random(0, 1);
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
} else {
return "paper wins";
}
}
if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
} else {
return "scissors wins";
}
}
if (choice1 === "scissors") {
if (choice2 === "rock") {
return " rock wins";
} else {
return "scissors wins"
}
}
}
compare(userGameChoice, computerChoice);
}
var input = function (userChoice) {
if (userChoice === "rock") {
return gamePlay("rock");
} else if (userChoice === "paper") {
return gamePlay("paper");
} else if (userChoice === "scissors") {
return gamePlay("scissors");
} else {
return "Invalid input";
}
}
input(prompt("Do you choose rock, paper or scissors?"));
var gamePlay=function(userGameChoice){
var computerChoice=Math.random(0,1);
如果(计算机选择<0.34){
computerChoice=“rock”;
}否则,如果(computerChoice我认为您希望执行以下操作:
var options = ["rock", "scissors", "paper"];
var userinput = prompt("Do you choose rock, paper or scissors?");
var gameResult = "Invalid Input";
if (options.indexOf(userinput) > -1) {
gameResult = gamePlay(userinput);
}
alert(gameResult);
这将获取用户输入并将其与有效选项列表进行比较。如果存在(-1
)然后,它将运行gamePlay
方法,将结果存储在变量gameResult中。您的gamePlay
函数不返回值。它调用compare
,该函数返回值,但因为gamePlay
没有返回语句,它实际上返回未定义的
如果你使用console.log(游戏性(“摇滚”);
你会看到未定义的
旁注:输入函数也可以使用switch语句而不是if/then/elses。注意,虽然Math.random(0,1)
可以工作(至少在某些浏览器中),但从技术上讲,它不接受任何参数,将忽略传递的参数,并始终传递从0(包括)到1(排除)的随机值。如果你想与之进行比较,这里有一个很好的实现:重新分配这样的函数会混淆代码的可读性。虽然它聪明而有用,但会使学习代码比平时困难一些。@Sukima我想我看错了问题,我以为OP试图不使用输入法。你的答案+1,我没有看到gamePlay
methodmakinggamePlay
to returncompare
中缺少的return
语句解决了这个问题。用我刚学到的有限知识编写了脚本,这就是为什么我不能使用其他已识别的方法。谢谢。