我正在尝试使用javascript的三元运算符语法编写这个if / else语句。是否可以将其写为三元运算符?
function changePlayer() {
if (currentPlayer === playerOne) {
currentPlayer = playerTwo
} else {
currentPlayer = playerOne
}
};
我目前的尝试是:
function changePlayer(){
currentPlayer === playerOne ? playerTwo : playerOne;
}
答案 0 :(得分:2)
你错过了作业陈述。所以最后的例子将是这样的:
function changePlayer(){
currentPlayer = (currentPlayer === playerOne) ? playerTwo : playerOne;
}
答案 1 :(得分:1)
三元运算符的第一个参数是条件:
function changePlayer(){
currentPlayer = (currentPlayer === playerOne) ? playerTwo : playerOne;
}