首页 > 解决方案 > If 语句中预期的声明或语句

问题描述

所以我正在编写一些代码来用 Javascript 构建一个简单的应用程序,其中计算机有一个随机数分配给石头、纸、剪刀,然后随机选择,然后还有一个用户选择。代码没有运行不知道为什么。

我尝试在determineWinner 函数的主if 语句内的if 语句末尾添加分号。

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
    return userInput;
  }else {
    console.log('Error, you must type rock, paper, or scissors');
  }
}

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

function determineWinner(userChoice, computerChoice){
  if(userChoice === computerChoice){
    return 'This game is a tie!'
  } else if(userChoice === 'rock'){
      if(computerChoice === 'paper'){
        return 'The computer has won!';
    }else{
      return 'The user has won';
    }
  } else if(userChoice === 'paper'){
      if(computerChoice === 'scissors'){
        return 'The computer has won!';
      }else(computerChoice === 'rock');{
        return 'The user has won!';
      }
    }else(userChoice === 'scissors');{
      if(computerChoice === 'rock'){
        return 'The computer has won!';
      }else(computerChoice === 'paper');{
        return 'The user has won!';
        }
    }
  } 
}

console.log(determineWinner('paper', 'scissors'));

在脚本末尾运行 console.log 时,它应该显示计算机已获胜。

标签: javascriptif-statement

解决方案


由于您所有的if案例都只是返回,因此您不需要使用else,因为 if-case 将始终返回。像这样:

function determineWinner(userChoice, computerChoice){
  if (userChoice === computerChoice) {
    return 'This game is a tie!'
  }
  if (userChoice === 'rock') {
    if(computerChoice === 'paper') {
      return 'The computer has won!';
    }
    return 'The user has won';
  }
  if (userChoice === 'paper') {
    if(computerChoice === 'scissors'){
      return 'The computer has won!';
    }
    return 'The user has won!';
  }
  if (userChoice === 'scissors') {
    if(computerChoice === 'rock') {
      return 'The computer has won!';
    }
    return 'The user has won!';
  } 
}

另一种方法是在函数末尾返回,答案如下:

function determineWinner(userChoice, computerChoice){
  const results = [
    'This game is a tie!', 
    'The computer has won!', 
    'The user has won!' 
  ];
  let winner;
  if (userChoice === computerChoice) winner = 0;
  else if (userChoice === 'rock') {
    winner = computerChoice === 'paper' ? 1 : 2;
  }
  else if (userChoice === 'paper') {
    winner = computerChoice === 'scissors' ? 1 : 2;
  }
  else if (userChoice === 'scissors') {
    winner = computerChoice === 'rock' ? 1 : 2;
  } 
  return results[winner];
}

推荐阅读