неопределенный вывод в простом JavaScript - PullRequest
1 голос
/ 05 августа 2020

Я новичок во всем этом и недавно начал изучать JavaScript. Чтобы проверить свои знания, я сделал этот простой сценарий «Камень, ножницы, бумага». Это что-то очень похожее на проект Codecademy. Проблема, с которой я столкнулся, связана с выводом, который отображается как «undefined», и я не могу понять, что дает этот вывод, может кто-нибудь помочь?

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();

  if (userInput === 'rock') {
    return 'Rock' 
  } else if (userInput === 'paper') {
    return 'Paper' }
    else if (userInput === 'scissors') {
    return 'Scissors'} 
    else if (userInput === 'bomb') {
      return 'Bomb'
    } else {
        return 'Please input a valid choice!'
      }
      }

const getComputerChoice = () => {
  const numbers = (Math.floor(Math.random() * 3))

  switch (numbers) {
    case 0 : return "Rock";
    break;
    case 1 : return "Paper";
    break;
    case 2 : return "Scissors";
    break;
  } 
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
      return 'It\'s a tie!!';
    } 
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
       return 'The Computer has won the game!!';
    } else {
        return 'Congratulation You have won the game!!';
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return ('The Computer has won the game!!');
    } else {
       return ('Congratulations You have won the game!!');
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'paper') {
      return 'Cogratulations You have Won the game!!';
  } else {
      return 'The Computer has won the game!!';
  }
}
  if (userChoice === 'bomb') {
    return 'Congratulation you Won!!'
  }

};

const playGame = () => {
  var userChoice =  getUserChoice('rock')
  var computerChoice = getComputerChoice()
 console.log('You picked: ' + userChoice);
 console.log('The computer picked: ' +computerChoice)

  console.log(determineWinner(userChoice, computerChoice));
}
 playGame()

Ответы [ 4 ]

2 голосов
/ 05 августа 2020

Ваши userChoice и computerChoice начинаются с заглавных букв. Вы сравниваете их со строчными строками. Кроме того, вы дважды проверяете наличие ножниц и не проверяете бумагу.

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();

  if (userInput === 'rock') {
    return 'Rock'
  } else if (userInput === 'paper') {
    return 'Paper'
  } else if (userInput === 'scissors') {
    return 'Scissors'
  } else if (userInput === 'bomb') {
    return 'Bomb'
  } else {
    return 'Please input a valid choice!'
  }
}

const getComputerChoice = () => {
  const numbers = (Math.floor(Math.random() * 3))

  switch (numbers) {
    case 0:
      return "Rock";
      break;
    case 1:
      return "Paper";
      break;
    case 2:
      return "Scissors";
      break;
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
    return 'It\'s a tie!!';
  }
  if (userChoice === 'Rock') {
    if (computerChoice === 'Paper') {
      return 'The Computer has won the game!!';
    } else {
      return 'Congratulation You have won the game!!';
    }
  }
  if (userChoice === 'Paper') {
    if (computerChoice === 'Rock') {
      return ('The Computer has won the game!!');
    } else {
      return ('Congratulations You have won the game!!');
    }
  }
  if (userChoice === 'Scissors') {
    if (computerChoice === 'Paper') {
      return 'Cogratulations You have Won the game!!';
    } else {
      return 'The Computer has won the game!!';
    }
  }
  if (userChoice === 'Bomb') {
    return 'Congratulation you Won!!'
  }

};

const playGame = () => {
  var userChoice = getUserChoice('rock')
  var computerChoice = getComputerChoice()
  console.log('You picked: ' + userChoice);
  console.log('The computer picked: ' + computerChoice)

  console.log(determineWinner(userChoice, computerChoice));
}
playGame()
0 голосов
/ 05 августа 2020

Тогда добро пожаловать в программирование! Комментарий выше верен - когда вы публикуете сообщение, постарайтесь точно указать c, какую именно проблему вы видите. Облегчает помощь.

С учетом сказанного, я думаю, глядя на приведенный выше код, я могу понять, что вы имеете в виду. При отладке часто бывает полезно просмотреть, как будет работать ваш код:

  1. вызывается playGame ()
  2. getUserChoice вызывается с параметром 'rock'
  3. userChoice присваивается 'Rock' * Примечание в верхнем регистре
  4. defineWinner вызывается с 'Rock' в качестве userChoice
  5. 'Rock' не запускает НИКАКИХ операторов if, а defineWinner ничего не возвращает

Итак, выполнив эти шаги, на самом деле довольно легко понять, почему defineWinner не определен при выходе из системы ... он ничего не возвращает. Смысл вашей функции getUserChoice, по-видимому, заключается в стандартизации входных данных. Но эти стандартизованные исходные данные в дальнейшем не используются должным образом. Вы могли бы сохранить эти возможные значения в массиве, а затем вернуть строчные значения из этой функции?

Надеюсь, это поможет - удачи!

0 голосов
/ 05 августа 2020

Выбранные значения начинаются с заглавной буквы, поэтому, например, вы хотите проверить, используется ли userChoice === 'Rock' вместо userChoice === 'rock'

Исправлено:

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();

  if (userInput === 'rock') {
    return 'Rock' 
  } else if (userInput === 'paper') {
    return 'Paper' }
    else if (userInput === 'scissors') {
    return 'Scissors'} 
    else if (userInput === 'bomb') {
      return 'Bomb'
    } else {
        return 'Please input a valid choice!'
      }
      }

const getComputerChoice = () => {
  const numbers = (Math.floor(Math.random() * 3))

  switch (numbers) {
    case 0 : return "Rock";
    break;
    case 1 : return "Paper";
    break;
    case 2 : return "Scissors";
    break;
  } 
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
      return 'It\'s a tie!!';
    } 
  if (userChoice === 'Rock') {
    if (computerChoice === 'Paper') {
       return 'The Computer has won the game!!';
    } else {
        return 'Congratulation You have won the game!!';
    }
  }
  if (userChoice === 'Scissors') {
    if (computerChoice === 'Rock') {
      return ('The Computer has won the game!!');
    } else {
       return ('Congratulations You have won the game!!');
    }
  }
  if (userChoice === 'Scissors') {
    if (computerChoice === 'Paper') {
      return 'Cogratulations You have Won the game!!';
  } else {
      return 'The Computer has won the game!!';
  }
}
  if (userChoice === 'Bomb') {
    return 'Congratulation you Won!!'
  }

};

const playGame = () => {
  var userChoice =  getUserChoice('rock')
  var computerChoice = getComputerChoice()
 console.log('You picked: ' + userChoice);
 console.log('The computer picked: ' +computerChoice)

  console.log(determineWinner(userChoice, computerChoice));
}
 playGame()
0 голосов
/ 05 августа 2020

Вы проверяете только Rock and Sciccors в своем методе определения победителя

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();

  if (userInput === 'rock') {
    return 'Rock' 
  } else if (userInput === 'paper') {
    return 'Paper' }
    else if (userInput === 'scissors') {
    return 'Scissors'} 
    else if (userInput === 'bomb') {
      return 'Bomb'
    } else {
        return 'Please input a valid choice!'
      }
      }

const getComputerChoice = () => {
  const numbers = (Math.floor(Math.random() * 3))

  switch (numbers) {
    case 0 : return "Rock";
    break;
    case 1 : return "Paper";
    break;
    case 2 : return "Scissors";
    break;
  } 
}

const determineWinner = (userChoice, computerChoice) => {
  if (userChoice === computerChoice) {
      return 'It\'s a tie!!';
    } 
  if (userChoice === 'Rock') {
    if (computerChoice === 'Paper') {
       return 'The Computer has won the game!!';
    } else {
        return 'Congratulation You have won the game!!';
    }
  }
  if (userChoice === 'Scissors') {
    if (computerChoice === 'Rock') {
      return ('The Computer has won the game!!');
    } else {
       return ('Congratulations You have won the game!!');
    }
  }
  if (userChoice === 'Paper') {//You mean paper here
    if (computerChoice === 'Rock') {
      return 'Cogratulations You have Won the game!!';
  } else {
      return 'The Computer has won the game!!';
  }
}
  if (userChoice === 'bomb') {
    return 'Congratulation you Won!!'
  }

};

const playGame = () => {
  var userChoice =  getUserChoice('rock')
  var computerChoice = getComputerChoice()
 console.log('You picked: ' + userChoice);
 console.log('The computer picked: ' +computerChoice)

  console.log(determineWinner(userChoice, computerChoice));
}
 playGame()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...