Home  >  Article  >  Web Front-end  >  JavaScript ternary operator usage examples_basic knowledge

JavaScript ternary operator usage examples_basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:03:451728browse

Ternary operator usage example:

The ternary operator as the name indicates requires three operands.

The syntax is condition ? result 1 : result 2;. Here you write the condition in front of the question mark (?) followed by result 1 and result 2 separated by a colon (:). If the condition is met, the result is 1, otherwise the result is 2.

Copy code The code is as follows:



Result: -------------------------- true
Copy code The code is as follows:



Result: -------------------------- false

Introduction to the ternary operator in programming languages ​​

This operator is rare because it has three operands. But it is indeed a type of operator because it also ultimately produces a value. This is different from the ordinary if-else statement described in the later section of this chapter. The expression takes the form:

Copy code The code is as follows:

Boolean expression ? Value 0: Value 1

If the "boolean expression" evaluates to true, "value 0" is evaluated, and its result becomes the value ultimately produced by the operator. But if the result of "Boolean expression" is false, "value 1" is evaluated, and its result becomes the value ultimately produced by the operator.

Of course, you can also use an ordinary if-else statement (described later), but the ternary operator is more concise. Although C is proud of being a concise language, and the ternary operator was probably introduced to reflect this efficient programming, if you plan to use it frequently, you still need to think more first - —It can easily produce code that is extremely unreadable.

A conditional operator can be used for its own "side effects", or for the values ​​it produces. But you should generally use it with values, because that clearly distinguishes the operator from if-else. Here is an example:

Copy code The code is as follows:

static int ternary(int i) {
return i < 10 ? i * 100 : i * 10;
}

It can be seen that if the above code is written using an ordinary if-else structure, the amount of code will be much larger than the above. As shown below:
Copy code The code is as follows:

static int alternative(int i) {
​if (i < 10)
return i * 100;
return i * 10;
}

But the second form is easier to understand and does not require more input. So when choosing a ternary operator, be sure to weigh the pros and cons.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn