Javascript has only one ternary operator "? ... :", which can be used for simple selection structures. The basic syntax is "Boolean expression? sentence1 : sentence2"; when the value of "Boolean expression" is When true, sentence1 is executed, otherwise sentence2 is executed.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.
javascript ternary operator
When the ternary operator in javascript is used for judgment, the basic syntax is: expression ? sentence1 : sentence2
When the value of expression
is true, execute sentence1
, otherwise execute sentence2
, Please look at the code
var b = 1, c = 1 a = 2; a >= 2 ? b++ : b--; b // 2 a < 2 ? c++ : c--; c // 0
From the above code, we will temporarily think that the ternary operator is equivalent to if else (more details below)
if(expression){ sentence1; } else { sentence2; }
When expression
is true , that is, sentence1# is executed when
expression is not
undefined,
NaN,
0,
null ##, otherwise execute
sentence2.
expression1 ? sentence1 : expression2 ? sentence2 : expression3 ? sentence3 : ...
if(expression1){ sentence1; } else if(expression2){ sentence2; } else if(expression3){ sentence3; } ...
Assignment
Another classic application scenario is assignment,var param = expression? value1 : value2, this I believe you often use
var b, c = 1; var a = b ? 2 : 1; a // 1 var a = c > 0 ? 2 : 1 a // 2
negotiate and negotiate again
One day I wrote such codefunction xx(){ var a = 1, b = 3; a < b ? return false : '' }
expression1 ? sentence1 : expression2 ? sentence2 : expression3 ? sentence3 : ...
if(expression){ return (return 2); }
var a = 1, b = 2; var c = b > 1 ? a++ : 0; c // 1
return a , return first and then add 1, so c here is equal to 1
Programming Video! !
The above is the detailed content of What are the ternary operators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!