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

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


我目前的尝试是:

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

最佳答案

您只是错过了分配声明。因此,最后一个示例将如下所示:

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

07-28 04:54