Ternary operator: bad or good practice? [duplicate

2019-01-26 03:32发布

I'm looking for reasons to use/not to use it and for original ideas (in their use and to replace them).


Duplicate:

Related (but does not address the question being asked):

5条回答
Juvenile、少年°
2楼-- · 2019-01-26 03:43

Good for short tags in templating languages like PHP, e.g:

<form>
<input type='radio' name='gender' value='m' <?=($gender=='m')?"checked":""?>>Male
<input type='radio' name='gender' value='f' <?=($gender=='f')?"checked":""?>>Female
</form>

Good for switches in javascript/jQuery:

var el = $("#something");
$(el).is(':visible') ? $(el).hide("normal") : $(el).fadeIn("normal");

Good for assignment, especially where a particular variable name can take different types:

$var = ($foo->isFoo()) ? 'Success!' : false;
查看更多
Bombasti
3楼-- · 2019-01-26 03:47

Which ternary operator are you talking about?

A ternary operator is any operator that takes three arguments.

If you're talking about the ? : operator, this is called the conditional operator. I can't live without it anymore, personally. If-else statements look so messy to me, especially when doing a conditional assignment. Some complain that it looks messy, but it is still possible (especially if using Visual Studio or another intelligent-formatting IDE) to make things easily readable, and you should be commenting all your conditionals anyway.

查看更多
迷人小祖宗
4楼-- · 2019-01-26 03:53

The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear. If the intent is not clear, it is best to use a temporary variable with a clear name whose value is assigned using an if-statement, or to use a function with a good name that returns the expected value.

查看更多
闹够了就滚
5楼-- · 2019-01-26 03:56

It's something like the for loop. Makes sense for what it's made for but when you try to stick more stuff in it, it becomes unreadable.

查看更多
三岁会撩人
6楼-- · 2019-01-26 04:00

For the sake of readability, I only use a ternary if it fits into one 80-char line.

查看更多
登录 后发表回答