[英]Alerts not opening from if statements
我正在制作剪刀石头布游戏,我希望警报来确定谁选择了什么以及谁赢得了比赛,但是警报不会弹出。 我发现有多个错误可以修复,并对其进行了重新检查,甚至进行了三重检查,但是警报仍然没有弹出?
这是三个功能之一(它们都是相似的):
function rock() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
}
if (computerChoice === "rock") {
alert("Link and Computer both chose Rock! It's a Tie!");
} else if (computerChoice === "scissors") {
alert("Link chose Rock and Computer chose Scissors! Computer took a heart of damage!");
} else {
alert("Link chose Rock and Computer chose Paper! Link took a heart of damage!");
}
}
您无法返回警报。 Alert是一个方法调用。 删除警报前面的退货,警报将打开:
if(computerChoice === "rock"){
alert("Link and Computer both chose Rock! It's a Tie!");
}
您不需要退货。 因此,更改此:
if(computerChoice === "rock"){
return alert("Link and Computer both chose Rock! It's a Tie!");
}
对此:
if(computerChoice === "rock"){
alert("Link and Computer both chose Rock! It's a Tie!");
}
我认为问题出在指示的行上:
function rock() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
} // <-- I don't think you want this closing brace here
if (computerChoice === "rock") {
alert("Link and Computer both chose Rock! It's a Tie!");
} else if (computerChoice === "scissors") {
alert("Link chose Rock and Computer chose Scissors! Computer took a heart of damage!");
} else {
alert("Link chose Rock and Computer chose Paper! Link took a heart of damage!");
}
}
我已经指出了右括号结束了rock()
函数。 就目前而言, rock()
函数实际上什么也没做。 它为局部变量随机分配一个值"rock"
, "paper"
或"scissors"
,但是该函数在不使用该变量的情况下结束,因此该值丢失了。
然后,当首次将JavaScript加载到浏览器中时,其余代码将运行一次。 此时, computerChoice
将是undefined
,因此您将收到一个JavaScript错误。
如果删除错误的括号,然后重新格式化代码,则会得到以下内容:
function rock() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
if (computerChoice === "rock") {
alert("Link and Computer both chose Rock! It's a Tie!");
} else if (computerChoice === "scissors") {
alert("Link chose Rock and Computer chose Scissors! Computer took a heart of damage!");
} else {
alert("Link chose Rock and Computer chose Paper! Link took a heart of damage!");
}
}
我多次运行了此功能。 每次它随机警告三个消息之一。
这有效并且使用较少的弯路到达那里:)
function rock() {
var replies = new Array(
'Link and Computer both chose Rock! It\'s a Tie!',
'Link chose Rock and Computer chose Scissors! Computer took a heart of damage!',
'Link chose Rock and Computer chose Paper! Link took a heart of damage!');
alert(replies[Math.floor(replies.length * Math.random())]);
}
澄清:Math.random()返回[0..1>
replies.length * Math.random()返回[0..3>
Math.floor(replies.length * Math.random())返回0、1或2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.