首页 > 解决方案 > Javascript抛出未定义

问题描述

所以我一直在努力学习编码并一直使用 codeAcademy 作为资源。我目前正在做一个石头、纸、剪刀练习,我的代码运行良好,但我最后一次console.log(determineWinner(userChoice, computerChoice));"将一个undefined扔进控制台。任何帮助,将不胜感激。

const getUserChoice = (userInput) => {
  userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

const getComputerChoice = () => {
  switch (Math.floor(Math.random() * 3)) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors';
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (getUserChoice === getComputerChoice) {
    return 'the game was a tie';
  }
}
if (getUserChoice === 'rock') {
  if (getComputerChoice === 'paper') {
    return 'computer won!';
  } else {
    return 'you won!';
  }
}
if (getUserChoice === 'paper') {
  if (getComputerChoice === 'scissors') {
    return 'computer won!';
  } else {
    return 'you won!';
  }
}
if (getUserChoice === 'scissors') {
  if (getComputerChoice === 'rock') {
    return 'computer won!';
  } else {
    return 'you won!';
  }
}
const playGame = () => {
  const userChoice = getUserChoice('rock');
  const computerChoice = getComputerChoice();
  console.log(`You threw: ${userChoice}`);
  console.log(`The computer threw: ${computerChoice}`);
  console.log(determineWinner(userChoice, computerChoice));
};
playGame();

标签: javascript

解决方案


忽略您在此处发布的代码中的一个小语法错误,非工作代码的问题是在函数determineWinner中,您有两个名为userChoice和的变量computerChoice。但是,错误地,您使用的是getUserChoiceand getComputerChoice

const getUserChoice = (userInput) => {
  userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

const getComputerChoice = () => {
  switch (Math.floor(Math.random() * 3)) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors';
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return 'the game was a tie';
  }

  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'computer won!';
    } else {
      return 'you won!';
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'scissors') {
      return 'computer won!';
    } else {
      return 'you won!';
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'computer won!';
    } else {
      return 'you won!';
    }
  }
}
const playGame = () => {
  const userChoice = getUserChoice('rock');
  const computerChoice = getComputerChoice();
  console.log(`You threw: ${userChoice}`);
  console.log(`The computer threw: ${computerChoice}`);
  console.log(determineWinner(userChoice, computerChoice));
};

playGame();


推荐阅读