if else 语句的编写方法
可以使用三元运算符编写 if-else
语句,例如
output = (val>val2) ? "Condition is true" : "Condition is false";
现在考虑
if(condition1){
//do something
}else if(condition2){
//do something
}else if(condition3){
//do something
}
如何使用三元运算符编写上述代码?
An if-else
statement can be written using ternary operator for e.g.
output = (val>val2) ? "Condition is true" : "Condition is false";
Now consider
if(condition1){
//do something
}else if(condition2){
//do something
}else if(condition3){
//do something
}
How to write above code using ternary operator ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
但请记住,如果条件数量超过 3 个,维护将是一场噩梦。
But keep in mind that in case, the number of conditions become more than 3, it will be a maintenance nightmare.
试试这个。
(a?w:(b?x:(c?y:z)))
Try this.
(a?w:(b?x:(c?y:z)))
扩展形式如下:
可以翻译成
但它很难读。
所以我建议将其提取到一个函数中并使用该函数代替。
Something in expanded form like this:
Can be translated into
But its pretty unreadable.
So I'd recommened extracting it into a function and using the function instead.
我想我明白了。您将需要类似的内容:
您只需将后续的 if 放在表达式最右侧的子句中即可。请注意,最后总会有一个默认情况。
I think i get it. You'll want something like:
You simply put subsequent ifs in the right-most clause of the expression. Note that there will always be a default case at the end.
当然。
您想要编写的是一个三元运算符作为 if else 语句。
好吧,让我们从逻辑上推断一下。
我们要说的是以下内容
就是这样!
快乐编码! ;)
Sure.
What you're trying to write is a ternary operator as an if else statement.
Well, let's logically deduce this.
What we're saying is the following
That's it!
Happy Coding! ;)
我会这样格式化它:
但我同意其他海报的观点,即嵌套三元运算符可能很难理解。
I would format it this way:
But I concur with other posters that nested ternary operators can be difficult to understand.
为什么?您编写的内容非常清楚,使用三元运算符不会更改生成的代码。
Why? What you've written is perfectly clear, and using the ternary operator won't change the generated code.