三元运算符和 if A, B, else C 有什么重要的区别吗?
在 javascript 中有几种方法可以做到这一点。
最重要的、最具可读性和灵活性的可能是:
if (a){
//b
}
else {
//c
}
其他仅*适用于赋值且可读性较差的东西是:
var foo = 'c';
if (a){
foo = 'b';
}
不过,我的主要问题是关于我能想到的最后两种方法:
var foo = a ? b : c;
var foo = a && b || c;
这两个表达式之间有什么区别吗? 除了两者都缺乏的可读性之外。
*尽管您可以将 foo 指定为一个函数,然后在 if 语句之后执行它。
There are a few ways to do this in javascript.
Foremost and most readable and flexible is probably:
if (a){
//b
}
else {
//c
}
Something else that only* works with assigning and is less readable is:
var foo = 'c';
if (a){
foo = 'b';
}
My main question, though, is about the last two methods I can think of:
var foo = a ? b : c;
var foo = a && b || c;
Are there any differences between these two expressions? Other than the readability which both lack.
*although you could assign foo to be a function, then execute it after the if statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设:
则:
两者不等价; 您永远不应该使用布尔运算符来代替条件运算符。 和其他回答者一样,我也认为条件运算符对于简单表达式并不缺乏可读性。
Suppose:
Then:
The two are not equivalent; you should never use the boolean operators in place of the conditional operator. Like other answerers, I also am of the opinion that the conditional operator does not lack readability for simple expressions.
三元运算符对我来说当然是可读的。 比第一个示例更重要的是,因为简洁的逻辑代码总是比执行相同操作的多行控制代码更容易理解。
The ternary operator is certainly readable to me. Even moreso than the first example, since concise, logical code is always easier to understand than many lines of control code that do the same thing.
我不同意第一个缺乏可读性,只要它使用正确,IOW a、b 和 c 本身就是简单的表达式。 该操作员确实会被滥用,尽管在不应该的情况下。
与第二个表达式类似,将结果 foo 用作布尔值以外的任何值都不好。 使用布尔运算符返回非布尔值,因为这就是它们的工作方式,这很令人困惑。 然而作为布尔表达式它是合理的。
I don't agree the first lacks readability as long as it is used correctly, IOW a, b and c are simple expressions themselves. This operator does get abused though in circumstances it ought not.
Similarly the second expression, using the result foo as anything other than a boolean would not be good. Using the boolean operators to return non-boolean values because thats the way they work is just confusing. However as a boolean expression its reasonable.
它们的计算结果不同,因为后者是布尔表达式,不使用三元运算符。
They do not evaluate to the same result as the latter is a boolean expression, not using a ternary operator.