三元运算符作为简短的条件语句
在 Javascript 中使用三元运算符代替较长的条件语句有什么问题吗,例如使用:
(variable == "dog") ? dog_stuff() : false;
而不是
if ( variable == "dog" )
{
dog_stuff();
}
这听起来像是一个愚蠢的问题,但我只是发现它非常快速且易于阅读,我只是不想成为如果存在可能的缺点,请使用它?
Is there anything wrong with using ternary operators in place of longer conditional statements in Javascript, for instance using:
(variable == "dog") ? dog_stuff() : false;
Rather than
if ( variable == "dog" )
{
dog_stuff();
}
This may sound like a stupid question but I just find it's pretty quick and easy to read, I just don't want to be using it if there's a possible drawback?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也可以这样写
如果没有 else 语句,
。 backbone.js 中的几行:
如果非常有必要,您可以对多个语句进行分组:
You could also write
if you don't have an else statement.
A few lines from backbone.js:
You can group multiple statements, if it's very necessary:
这是错误的,因为您告诉代码执行
false
。想象一下下面的代码:在我看来,4 行条件函数调用完全没问题。您可以将其简写为:
唯一的问题是,如果您将其注释掉,或者添加 1 个以上的函数,那么事情看起来是正确的,但无法正确执行:
It's wrong because you're telling your code to execute
false
. Imagine the following code:IMO the 4 line conditional function call is perfectly fine. You can shorthand it to:
The only problem with this is if you comment it out, or add 1 more function then things look correct, but don't execute correctly:
只要您和其他可能需要阅读代码的人能够轻松理解该格式,就可以了。
As long as the format is easily understood by you and anyone else that may need to read the code, it's fine.