我的控制台只返回两个输入或只返回一个

时间:2018-02-18 21:30:15

标签: javascript

这是我第一次发帖,我在控制台上生成所有选择时遇到问题。如果我在底部使用摇滚乐,那么它只会显示出剪刀"剪刀"结果。如果我不把它大写,它只会显示另外两个结果,而不是剪刀。任何指导都会有所帮助。

function computerPlay() {
    let selection = ["Rock", "Paper", "Scissors"];
    let computerSelection = selection[Math.floor(Math.random() * selection.length)];
    return computerSelection;
}

function playRound(playerSelection, computerSelection) {
    if (playerSelection === "Rock") {
        if (computerSelection === "Scissors")
            return "You win mate, cheers!";
    } else if (computerSelection === "Paper") {
        return "You lost lad";
    } else {
        return "Draw";
    }
}
const playerSelection = "rock"
const computerSelection = computerPlay()
console.log(playRound(playerSelection, computerSelection))

3 个答案:

答案 0 :(得分:0)

问题在于,如果玩家选择匹配" Rock",则忽略else ifelse块,然后查看计算机是否选择了Scissors。如果是这种情况,你就会回归"你赢得了伴侣,欢呼!",否则你就不会回报任何东西,这就是你未定义的原因。如果玩家不玩Rock,那么你进入其他任何一个if or else声明,但玩家永远不会赢。

以下是playRound功能可能正常工作的内容:

function playRound(player, comp) {
    const selection = ["Rock", "Paper", "Scissors"];

  pl = selection.indexOf(player);
  co = selection.indexOf(comp);

  if (co === pl) { 
    return 'Draw';
  } else if (co - pl == 1) { 
    return 'You lost lad' 
  } else { 
    return 'You win mate, cheers!' 
  }
}

这是一个有工作代码示例的jsfiddle:https://jsfiddle.net/qjp1y1mg/

答案 1 :(得分:0)

这段代码对我来说很好。试试这个。这是你的代码,但是出了点问题(在错误的地方有一个括号),我已经改变了它。

    function playRound(playerSelection, computerSelection) {
        if (playerSelection === "Rock"){
             if (computerSelection === "Scissors") 
                  return "You win mate, cheers!";

              else if (computerSelection === "Paper"){        
                   return "You lost lad";
             }
            else {return "Draw";}
         }
      }

在您的代码中,此括号错误。因为您要排除其他事件

   if (playerSelection === "Rock") {
           if (computerSelection === "Scissors")
                return "You win mate, cheers!";
         **}**

答案 2 :(得分:0)

在第一个内部if语句之后,你错过了一个大括号。代码的缩进应该表明它没有按照你想要的方式嵌套。

function playRound(playerSelection, computerSelection) { 
    if (playerSelection === "Rock") { 
        if (computerSelection === "Scissors"{ 
            return "You win mate, cheers!"; 
        } else if (computerSelection === "Paper") { 
            return "You lost lad"; 
        } else { 
            return "Draw"; 
        } 
    }
}

这里修好了。在将来扫描您的代码并问自己哪个左括号对应于右括号。