使用If/else时javascript出现一些问题
我正在通过Codecademy学习JavaScript。在那里我被要求做一个石头纸剪刀游戏。我是通过编写以下代码来实现的:使用If/else时javascript出现一些问题,javascript,Javascript,我正在通过Codecademy学习JavaScript。在那里我被要求做一个石头纸剪刀游戏。我是通过编写以下代码来实现的: var userChoice = prompt("Do you choose rock, paper or scissors?"); var computerChoice = Math.random(); if (computerChoice < 0.34) { computerChoice = "rock"; } else if (computerChoic
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"
}
} 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);
为了检查,我输入了“dog”,但它没有显示“unavailable”
应该是
console.log("unavilable")
您还需要调用函数a
:
compare(userChoice, computerChoice);
a();
更新:
if (userchoice !== "scissors") { //Problem is here "userChoice" and not "userchoice"
请参阅。最好在条件下
if(userchoice!="..." && userchoice!="...")
console.log(...)
甚至使用
switch(userchoice)
case: "rock":
case: "paper":
console.log(...);
break;
您用
userChoice
错误地键入了userChoice
我建议您在Array中实现一种方法。这样代码的可读性会更高。下面是它的代码:
function inArray(needle, haystack){
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
功能inArray(针、草垛){
var length=haystack.length;
对于(变量i=0;i
那么您只是在代码中调用它。下面是一个包含完整代码的JSFIDLE:那么,问题出在哪里?您不应该使用
如果
block你的问题是什么?为了检查,我键入了“dog”,但它没有显示“unavailable”@srijanpoudel。如何调用函数a()
?函数a没有任何参数,使用的变量“userChoice”是在最上面定义的。var userChoice=prompt(“您选择石头、布还是剪刀?”)@斯里詹普德尔。您不必传递任何参数,只需像我那样调用它。还有,我说的是abt拼写错误。C是userChoice中的caps。我给你添了一把小提琴。
switch(userchoice)
case: "rock":
case: "paper":
console.log(...);
break;
function inArray(needle, haystack){
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}