Rob*_*Rob 5 javascript coding-style ternary-operator
如果您首先讨厌三元条件运算符,则无需回复;)
我经常看到这与分配表达式一起使用,如:
var foo = (some_condition) ? then_code : else_code;
Run Code Online (Sandbox Code Playgroud)
但是,我想用它来代替简单的代码,例如:
if(some_condition) {
do_something_simple;
} else {
do_something_else;
}
Run Code Online (Sandbox Code Playgroud)
而是做:
(some_condition) ? do_something_simple : do_something_else;
Run Code Online (Sandbox Code Playgroud)
我可能会在JavaScript中这样做.在上面它返回undefined,因此它不需要赋值.我喜欢节省的空间但是想知道人们对这种用途的看法,同样,我通常只看到三元用于作业.
编辑:我看到答案暗指"隐藏意图".虽然在表达式中经常使用,但是如何在表达式中隐藏意图呢?特别是在动态语言中,人们可能会看到遍布各地的三元运算符?
条件运算符通常应在表达式(值生成表达式)中使用,并且最好不要用作“if/then/else”语句的替代。偶尔用一下,不会有什么特别的问题;如果系统地使用,我认为这会向读者隐藏代码的意图。