javascript三元运算符反对if / else

时间:2016-01-10 22:50:59

标签: javascript ternary-operator

我正在尝试使用javascript的三元运算符语法编写这个if / else语句。是否可以将其写为三元运算符?

function changePlayer() {
            if (currentPlayer === playerOne) {
                currentPlayer = playerTwo
            } else {
                currentPlayer = playerOne
            }
        };

我目前的尝试是:

function changePlayer(){
      currentPlayer === playerOne ? playerTwo : playerOne;
}

2 个答案:

答案 0 :(得分:2)

你错过了作业陈述。所以最后的例子将是这样的:

function changePlayer(){
      currentPlayer = (currentPlayer === playerOne) ? playerTwo : playerOne;
}

答案 1 :(得分:1)

三元运算符的第一个参数是条件:

function changePlayer(){
  currentPlayer = (currentPlayer === playerOne) ? playerTwo : playerOne;
}