Home > Article > Web Front-end > Various techniques for using JavaScript ternary operator_javascript techniques
I find that when I write too much code, I will unconsciously replace if else with ternary. It just makes the code more concise and incisive. Of course, some people say that using ternary can make you have a climax. I also felt this way when I was writing js recently, and I collected some tips to share.
Big Bird, please skip the following paragraph, Big Bird can help correct it ^__^
====Popular Line====
Expression (expr1) ? (expr2) : (expr3)
The value is expr2 when expr1 evaluates to TRUE, and the value is expr3 when expr1 evaluates to FALSE.
============
Common usage
When you find that you often use if else
There are often such if else judgments in daily life, especially when there are many nestings. It is more harmonious to use ternary, which can make your code look more refreshing and have a clear structure.
Slightly smarter usage
Through constant changes, many usages of ternary can be derived. The following jquery code
Upgrade it again
You can call the functions you want as needed to handle more things.
flag ? a() : b();
Then the complete body of the teacher
So there is such a case, two buttons, one for forward behavior and one for backward behavior. The operating functions are almost the same.
var btn_next = $('#item-photo-panel a.next')
btn_next.click(function(){
action_turn(this, 'next');
return false;
});
var btn_prev = $('#item-photo-panel a.prev')
btn_prev.click(function(){
action_turn(this, 'prev');
return false;
});
Note: Note that the ternary operator is a statement, so its evaluation is not a variable, but the result of the statement. This is important if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a function that returns by reference will not work, and a future version of PHP will issue a warning about this.
However, after testing, I found that the above approach can work in javascript. This is probably because js is not as rigorous as BT compared to php.