简体   繁体   中英

javascript ternary operator opposed to if/else

I am trying to write this if/else statement using javascript's ternary operator syntax. Is it possible to write this as a ternary operator?

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

My current attempt is:

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

You just miss the assignment statement. So the final example will go like this:

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

The first argument of the ternary operator is the condition:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM