?操作员不工作
这怎么不可能呢?我的表达开始非法。
(s1.charAt(i) == ' ') ? i++ : break;
How come this is not possible? I am getting illegal start of expression.
(s1.charAt(i) == ' ') ? i++ : break;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这里需要理解的是,?: 运算符用于返回值。您基本上是在该行中调用一个如下所示的函数:
没有意义,对吧? ?: 运算符仅被设计为上述 if/else 返回语句的简写,而不是完全替代 if/else。
The thing to understand here is that the ?: operator is used to return a value. You're basically calling a function that looks like this in that line:
Makes no sense, right? The ?: operator was only designed as a shorthand for if/else return statements like the above, not a replacement of if/else altogether.
您不能在三元条件表达式的一部分中使用
break
,因为break
本身不是表达式,而只是一个控制流语句。为什么不直接使用 if-else 结构呢?
You cannot use
break
in part of a ternary conditional expression asbreak
isn't an expression itself, but just a control flow statement.Why not just use an if-else construct instead?
三元运算符是一个表达式,而不是一个语句。为此,请使用
if ... else ...
。The ternary operator is an expression, not a statement. Use
if ... else ...
for this.当然有效。但它是一个运营商。从什么时候开始,诸如“break”之类的语句成为了操作数?
Of course it works. But it's an operator. Since when was a statement such as 'break' an operand?
我建议避免使用三元 (?:) 运算符,除非是简单的赋值。在我的职业生涯中,我见过太多疯狂的嵌套三元运算符;它们成为令人头疼的维护问题(更多的认知超载 - “不要让我思考!”)。
我不会禁止我的团队使用它们,但建议明智地使用它们。仔细使用它们比相应的 if/else 结构更清晰: -
与三元替代方案相比: -
三元版本是: -
I recommend avoiding the ternary (?:) operator EXCEPT for simple assignments. In my career I have seen too many crazy nested ternary operators; they become a maintenance headache (more cognitive overload - "don't make me think!").
I don't ban them on my teams, but recommend they are used judiciously. Used carefully they are cleaner than a corresponding if/else construct: -
Compared to the ternary alternative: -
The ternary version is: -