簡體   English   中英

else 語句中的三元運算符在此示例中如何工作?

[英]How does the ternary operator in the else statement work in this example?

雖然問題很老,但仍然讓我很困惑

如果您看過 javascript udemy 課程...

在豬游戲中,這個家伙創造了他說

If(dice !== 1) {
//Let's assume I've created my roundscore and other variables
}

/*What really baffles me is when he got to else statements he said */

else {
activePlayer === 0? activeplayer = 1 : activeplayer = 0
}

//Please why can't he say 

else if (dice === 1){
activeplayer = 1
}

/*Please I need a clear explanations */

三元運算符和 if/else 語句可以互換,並且在大多數情況下都可以代替其他運算符。 在您的情況下, if 語句檢查骰子是否不等於 1,然后轉到 else 語句。 在這里,代碼檢查 activePlayer 變量是否等於 0:如果是,則將變量設置為 1,否則將變量設置為 0。

但是,if 語句似乎有一個錯誤,因為當 if 條件滿足時,代碼不會考慮 else 語句,這意味着 else 語句只有在變量 = 1 時才會運行,這意味着三元運算符是多余的。 再看看你的問題,我相信你的代碼甚至視頻都有錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM