可以使用三元运算符编写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
}如何使用三元运算符编写上述代码?
发布于 2011-10-26 17:18:04
output = (condition1) ?
"First Case" : ((condition2) ?
"Second Case" : ( (condition3) ?
"Third Case") : (...));但要记住,万一条件数超过3个,那将是一场维修噩梦。
发布于 2011-10-26 14:55:03
尝尝这个。
(a?w:(b?x:(c?y:z)))
发布于 2011-10-26 14:56:56
扩展后的内容如下所示:
X outputfn( ... )
{
if(c1) { return A; }
else if(c2) { return B; }
else { return C; }
}
output = outputfn(...);可以翻译为
output = (c1)?A:((c2)?B:C);但是它很难读。
因此,我建议将其提取到一个函数中,并改用该函数。
https://stackoverflow.com/questions/7899497
复制相似问题