【问题标题】:Ternary Condition for if { } else if { if { } else { } }if { } else if { if { } else { } } 的三元条件
【发布时间】:2019-04-11 07:55:15
【问题描述】:

我想将所有 if else 语句更改为三元运算符。这个 if else 语句的三元运算符是什么?

  const compareHands = (playerChoice, computerChoice) => {
        // Update Text
        const winner = document.querySelector('.winner');
        const winnerIs = (who, isPlayerWin) => {

            winner.textContent = `${who} Wins!`;

            isPlayerWin ? pScore++ : cScore++;

            updateScore();
        };



        // Check for tie
        if (playerChoice === computerChoice) {
            winner.textContent = 'It Is A Tie!';
            // Check For Winner
        } else if (playerChoice === 'rock') {
            if (computerChoice === 'scissors') {
                winnerIs('Player', true);
            } else {
                winnerIs('Computer', false);
            }
        } else if (playerChoice === 'paper') {
            if (computerChoice === 'scissors') {
                winnerIs('Computer', false);
            } else {
                winnerIs('Player', true);
            }
        } else if (playerChoice === 'scissors') {
            if (computerChoice === 'rock') {
                winnerIs('Computer', false);
            } else {
                winnerIs('Player', true);
            }
        }
    }

【问题讨论】:

标签: javascript conditional-statements ternary


【解决方案1】:

老实说,我不认为使用三元运算符会使代码变得更好。 我建议您尝试通过创建一个易于查找的数据结构来减少 if-else 链,如下所示:


const whatBeats = {
  'scissors': 'rock',
  'paper': 'scissors',
  'rock': 'paper'
};
const compareHands = (playerChoice, computerChoice) => {
  // Update Text
  const winner = document.querySelector('.winner');
  const winnerIs = (who, isPlayerWin) => {

    winner.textContent = `${who} Wins!`;

    isPlayerWin ? pScore++ : cScore++;

    updateScore();
  };

  // Check for tie
  if (playerChoice === computerChoice) {
    winner.textContent = 'It Is A Tie!';
    // Check For Winner
  } else if (playerChoice === whatBeats[computerChoice]) {
    winnerIs('Player', true);
  } else {
    winnerIs('Computer', false)
  }
}

在这种情况下,我们将游戏动态视为数据,将其集中在一个地方。

对于接下来的问题,尝试解决之前的问题(关于三元运算符的教程有很多)。

【讨论】:

    【解决方案2】:

    试试这样。虽然可读性是一个问题,因为嵌套的if else 太多,被三元运算符取代。 true & false 分别替换为 !0 & !1 以缩短语句

    playerChoice === computerChoice ?
      winner.textContent = "It Is A Tie!" :
      "rock" === playerChoice ?
      "scissors" === computerChoice ?
      winnerIs("Player", !0) :
      winnerIs("Computer", !1) :
      "paper" === playerChoice ?
      "scissors" === computerChoice ?
      winnerIs("Computer", !1) :
      winnerIs("Player", !0) :
      "scissors" === playerChoice && ("rock" === computerChoice ? winnerIs("Computer", !1) :
        winnerIs("Player", !0));

    【讨论】:

    • @AKX 总有比最好的更好的方法。我刚刚回答了 SO 用户提出的问题。我本可以建议他使用对象映射而不是嵌套 if.. else 人们已经做过的事情,但这不是他问题的答案
    • @brk 是的,我的意思不是批评——你确实回答了 OP 的问题,只是没有人真的应该在“生产”中这样做:)
    【解决方案3】:

    正如 Nina Scholz 所说,我也不会使用。我知道这并不能回答字面上的问题,但是这个怎么样呢?

    const loser_to = {
      paper: 'rock',
      rock: 'scissors',
      scissors: 'paper'
    };
    
    if (loser_to[playerChoice] === computerChoice) {
      // player wins
    } else if (loser_to[computerChoice] === playerChoice) {
      // computer wins
    } else {
      // noone wins
    }
    

    【讨论】:

      【解决方案4】:

      使用过多的三进制可能会导致代码不可读。我建议你可以使用 switch case 结合三元运算符。

      switch (playerChoice) {
         case computerChoice: winner.textContent = 'It Is A Tie!';break;
         case 'rock': computerChoice === 'scissors' ?  winnerIs('Player', true) : winnerIs('Computer', false); break;
         case 'paper': computerChoice === 'rock' ?  winnerIs('Player', true) : winnerIs('Computer', false); break;
         case 'scissors': computerChoice === 'paper' ?  winnerIs('Player', true) : winnerIs('Computer', false); break;
          }
      

      【讨论】:

        【解决方案5】:

        如果您想要更干燥的代码。您可以尝试此解决方案以避免多次调用winnerIs 函数。

        const compareHands = (playerChoice, computerChoice) => {
          const winner = document.querySelector('.winner');
        
          if (playerChoice == computerChoice) {
            winner.textContent = 'It Is A Tie!';
            return;
          }
        
          let choices = ['rock', 'paper', 'scissor'];
          let playerIndex, computerIndex, isPlayerWin;
        
          playerIndex = choices.indexOf(playerChoice);
          choices.push(choices.shift());
          computerIndex = choices.indexOf(computerChoice);
          isPlayerWin = playerIndex !== computerIndex;
        
          winner.textContent = `${isPlayerWin ? 'Player' : 'Computer'} Wins!`;
          isPlayerWin ? pScore++ : cScore++;
          updateScore();
        }
        

        【讨论】: