Remembering the Ternary Operator Syntax

2019-02-13 15:30发布

Anyone have a good trick to remember the standard ternary syntax?

Specifically whether the '?' or ':' comes first. I have consistently gotten this backwards over the years.

7条回答
叛逆
2楼-- · 2019-02-13 16:15

As far as remembering which symbol comes first, I just think of the fact that the first part is a question, "Is it true or not?", so the question mark goes first.

I think of the syntax in this manner

Question ? Yes : No
查看更多
爷的心禁止访问
3楼-- · 2019-02-13 16:18

Think of it this way: a ternary statement consists of three parts: the question, the code to execute if the answer to the question is "yes" and the code if the answer is "no". The "?" comes after the question like it does in English sentences.

查看更多
放我归山
4楼-- · 2019-02-13 16:20

If you're unit tests still pass when you get it wrong, then either it doesn't matter or your tests aren't covering enough of the paths through the code. If there's too long a gap between typing it and getting a pass/fail from the tests, that's another issue. Very few little syntax nits matter in the presence of good, fast tests.

查看更多
趁早两清
5楼-- · 2019-02-13 16:26

in python I read it as a normal English sentence:

 a equals b if condition is true else c
查看更多
我只想做你的唯一
6楼-- · 2019-02-13 16:27

The condition you are checking is kind of like a question, so the question mark comes first.

x > 0 ? 1 : 0

Think of this statement as three English sentences: "Is x greater than 0? Then 1. Else, 0." You have one sentence for each clause in the statement.

The predicate:

x > 0 ? /* Is x greater than 0? */

The "true" branch:

1 /* Then 1. */

The "false" branch:

: 0 /* Else, 0. */
查看更多
对你真心纯属浪费
7楼-- · 2019-02-13 16:33

It goes like this:

myVariable = this.testMethod() ? 'value for true case' : 'value for false case'
查看更多
登录 后发表回答