如何使用三元运算符退出函数
Posted
技术标签:
【中文标题】如何使用三元运算符退出函数【英文标题】:how to exit a function using the ternary operator 【发布时间】:2020-04-30 13:01:38 【问题描述】:我这里有这个不完整的代码
document.querySelector('.btn-hold').addEventListener('click', function()
scores[activePlayer] += roundScore
document.querySelector("#score-" + activePlayer).textContent = scores[activePlayer]
//checking if the player won the game
scores[activePlayer] === 20? /*exit the function*/ : /*move to the next player*/ nextPlayer()
)
我尝试了“返回”,但它出错了。
【问题讨论】:
if(scores[activePlayer] !== 20) nextPlayer();
三元运算符通常对简短的语句很有用。但是请不要仅仅为了使用而使用它。如果条件通过时你不想做任何事情,那么三元运算符在这里没有它的位置
如果您不需要结果值,请不要使用三元运算符表达式。
不过为了好玩,一个简短的形式是scores[activePlayer] === 20 || nextPlayer()
。
@blex 哦,谢谢你帮我解决这个问题。
【参考方案1】:
三元运算符对于控制流来说是不必要的,如果你试图从运算符返回一个值,它会更有用。您应该考虑将其简化为简单的if
语句。
if (scores[activePlayer] !== 20)
nextPlayer();
如果为 false 则让函数自然退出。
【讨论】:
哦,谢谢,问题是我只是在学习课程,导师使用了 if else 语句,但我想我可以用另一种方式来做,以上是关于如何使用三元运算符退出函数的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 JavaScript 中的三元运算符更改函数中的 if else 语句?