我正在做练习,而且我在使用代码时遇到了一些问题。我花了一些时间来计算使用差异的岩石剪刀配方,而不是用if来键入每个场景。但我在尝试使其在www.repl.it中运行时遇到了一些问题
var rock = 0
var paper = 1
var scissors = 2
var computerMove = rock;
var playerMove = paper;
function getWinner(playerMove,computerMove) {
var winner;
if (computerMove == playerMove){
console.log("draw")
}
else if ((playerMove - computerMove + 3) % 3 == 1){
var winner = "player"
}
else {
winner = "computer"
}
return winner;
}
我之前从未使用过功能,我知道确定获胜者的公式是正确的,但我无法将任何内容分配给变量"胜利者"。我在这里没有收到任何错误,但赢家似乎什么都没有。
任何帮助?
答案 0 :(得分:2)
好吧,如果这是您的整个代码,那么您就错过了该函数的实际调用。
函数的目标是编写可重用的过程,您可以多次调用它。
var rock = 0
var paper = 1
var scissors = 2
var computerMove = rock;
var playerMove = paper;
function getWinner(playerMove,computerMove) {
var winner;
if (computerMove == playerMove){
console.log("draw")
}
else if ((playerMove - computerMove + 3) % 3 == 1){
var winner = "player"
}
else {
winner = "computer"
}
return winner;
}
var winner = getWinner(playerMove, computerMove);
console.log( winner );
另外,你错过了领带条件。
您可以在" tie"中启动内部winner
var状态,并覆盖" tie"如果你遇到病情。
答案 1 :(得分:2)
您可能希望继续学习功能。从上面的代码中,您实际上从未调用过该函数。您还应该更好地格式化代码,使其更具可读性。这应该有效:
var rock = 0;
var paper = 1;
var scissors = 2;
var computerMove = rock;
var playerMove = paper;
var winner;
function getWinner(playerMove, computerMove) {
if (computerMove == playerMove) {
winner = "draw";
} else if ((playerMove - computerMove + 3) % 3 == 1) {
winner = "player";
} else {
winner = "computer";
}
return winner;
}
console.log(getWinner(playerMove, computerMove));
答案 2 :(得分:0)
你在其中一个条件中胜过胜利者,而且我没有看到你在哪里调用getWinner函数。
var rock = 0
var paper = 1
var scissors = 2
var computerMove = rock;
var playerMove = paper;
function getWinner(playerMove,computerMove) {
var winner;
if (computerMove == playerMove)
{
console.log("draw");
}
else if ((playerMove - computerMove + 3) % 3 == 1)
{
winner = "player";
}
else
{
winner = "computer";
}
return winner;
}
$(function(){
$('#txtWinner').text(getWinner(playerMove, computerMove));
});
使用工作代码查看此plunker: http://plnkr.co/edit/EEWbdjsp0aHR87Tx2OER?p=preview
答案 3 :(得分:0)
请参阅代码中的注释以获取解释:
var rock = 0
var paper = 1
var scissors = 2
var computerMove = rock;
var playerMove = paper;
//declare variable outside the function if you want to be able to access it from outside of the function (look into variable scope)
var winner;
function getWinner(playerMove,computerMove) {
if (computerMove == playerMove){
// set a value in case of draw
winner = "draw"
}
else if ((playerMove - computerMove + 3) % 3 == 1){
// don't redeclare the variable!
winner = "player"
}
else {
winner = "computer"
}
return winner;
}
//call the function so it actually executes
getWinner(playerMove,computerMove);
//this should print out your answer now
console.log(winner);