简体   繁体   English

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

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

Though the question is old but still baffles me alot虽然问题很老,但仍然让我很困惑

If you've watched the javascript udemy course...如果您看过 javascript udemy 课程...

In the pig game the guy created he said在猪游戏中,这个家伙创造了他说

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 */

Ternary operators and if/else statements can be interchangeable and either can be used in the place of others in most cases.三元运算符和 if/else 语句可以互换,并且在大多数情况下都可以代替其他运算符。 In your case, the if statement checks if the dice does not equal one, then goes to the else statement.在您的情况下, if 语句检查骰子是否不等于 1,然后转到 else 语句。 In here the code checks if the activePlayer variable is equal to zero: if it is, then the variable is set to 1 and if not the variable is set to 0.在这里,代码检查 activePlayer 变量是否等于 0:如果是,则将变量设置为 1,否则将变量设置为 0。

However, there seems to be a mistake in the if statement as when the if condition is satisfied, the code will not regard the else statement, meaning the else statement will only run if the variable = 1, meaning the ternary operator is redundant.但是,if 语句似乎有一个错误,因为当 if 条件满足时,代码不会考虑 else 语句,这意味着 else 语句只有在变量 = 1 时才会运行,这意味着三元运算符是多余的。 Look over your question again and see, I believe there is a mistake in your code or even the video.再看看你的问题,我相信你的代码甚至视频都有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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