In JavaScript, the ternary operator does not have an equal sign. It is composed of a question mark and a colon. The syntax format is "Conditional expression? Expression 1: Expression 2;"; if "Conditional expression If the result of "expression" is true (true), then the code in "expression 1" will be executed, otherwise the code in "expression 2" will be executed.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Ternary operator in javascript
Ternary operator (also known as ternary operator, conditional operator), It consists of a question mark and a colon, and the syntax format is as follows:
条件表达式 ? 表达式1 : 表达式2 ;
"Conditional expression" must be a Boolean expression, and "Expression 1" and "Expression 2" are values of any type .
If the result of "conditional expression" is true (true), the code in "expression 1" is executed and the value of the expression is returned.
If the result of "conditional expression" is false (false), the code in "expression 2" is executed and the value of the expression is returned.
Example:
Define variable a, then check whether a is assigned a value, if assigned, use the value; otherwise set the default value.
var a = null; //定义变量a typeof a != "undefined" ? a = a : a = 0; //检测变量a是否赋值,否则设置默认值 console.log(a); //显示变量a的值,返回null
The conditional operator can be converted into a conditional structure:
if(typeof a != "undefined"){ //赋值 a = a; }else{ //没有赋值 a = 0; } console.log(a);
can also be converted into a logical expression:
(typeof a != "undefined") && (a =a) || (a = 0); //逻辑表达式 console.log(a);
In the above expression, if a has been assigned, then Execute the (a = a) expression. After execution, the (a = 0) expression following the logical OR operator will no longer be executed; if a is not assigned a value, the (a = a) expression following the logical AND operator will no longer be executed. expression, and instead executes the expression following the logical OR operator (a = 0).
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How many equal signs does the javascript ternary operator have?. For more information, please follow other related articles on the PHP Chinese website!