A variety of tips for using JavaScript ternary operators
found that the code slowly write more time will be unconsciously to replace if else with ternary, just to make the code more concise and incisive, of course, some people say with ternary can let you have the feeling of orgasm. Recently in writing JS also have this feeling, and collected some tips, share sharing.
Big Bird Please skip the following paragraph, Big Bird help correct ^__^
= = Universal Line = = =
An expression (EXPR1)? (EXPR2): (EXPR3)
When EXPR1 evaluates to TRUE, the value is EXPR2, and the value is EXPR3 when the EXPR1 evaluates to FALSE.
============
General usage
When you find that you often use if else
The code is as follows:
if (Bai Chun | |) {
Non-hanging section;
}else{
Door-door hanging;
}
So the ternary notation is
The code is as follows:
Brother Bai Chun | | The exam Emperor? Non-hanging section: Door Door hanging
The very handsome discovery code brilliantly is many.
There are often such if else judgments in daily life, especially when nesting more than three times is more harmonious, you can make your code look more refreshing, the structure is clear.
A little bit smarter usage
Through constant changes, many ternary usages can be derived. The following section of the jquery code
The code is as follows:
Flag? $ (' body '). addclass (' hover '): $ (' body '). Removeclass (' hover ');
Even more perverted.
The code is as follows:
$ ('. Item ') [flag? ' AddClass ': ' Removeclass '] (' hover ')
The above code looks more confused. Because when flag = True, the code becomes the following code:
The code is as follows:
$ ('. Item ') [' AddClass '] (' hover ')
This is the equivalent of.
The code is as follows:
$ ('. Item '). addclass (' hover ')
Just a little bit.
You can invoke the function you want to handle more things as needed.
The code is as follows:
function A () {
Do something
}
Function B () {
Do something
}
Flag? A (): B ();
Then the complete body of the teacher
So with this case, two buttons a forward behavior, a backward behavior. The functions of the operation are similar.
The code is as follows:
var Action_turn = function (e, type) {
var self = $ (e). Closest (' Li ');
var target = Self[type = = = ' prev '? ' prev ': ' Next ' ();
Target.addclass (' has-img ');
Self.removeclass (' has-img ')
}
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;
});
Try to avoid the situation
The code is as follows:
Alert (true?) ' True ': false? ' t ': ' F ')
I mean to avoid as much as possible nested ternary, because in JS the statement is from right to left, the above code is equivalent to
The code is as follows:
Alert (true?) ' True ': (false?) ' t ': ' F '))
As in PHP, this result is completely different, ternary nesting time is the first left.
The code is as follows:
Echo (true? ' True ': false)? ' t ': ' F ') in//php
Tip
Also found in PHP ternary has such a hint
Note: Notice that the ternary operator is a statement, so its evaluation is not a variable, but rather a result of the statement. This is important if you want to return a variable by reference. In a function returned by reference, return $var = = 42? $a: $b; Will not work, a warning will be issued for future versions of PHP.
But after testing, found in JavaScript above the practice can be useful, probably JS compared to BT, the rigor of the reason is not as large as PHP.
Today talk about a small knowledge point, ternary operator. Ternary operations, as the name implies there will be three elements, the approximate composition of the expression of condition? EXPR1:EXPR2; a statement with two expressions. The question mark is preceded by a judgment statement. If true, the first expression is executed, and if False, the second expression is executed. My understanding is actually a simplified if else statement, with a chestnut, often see a click to expand, and then click the Hide button.
I would like to implement the Click Input method, the implementation of the following UL expand and hide, if we use if else words may be written like this:
Obth.onclick= Function () {if ( Oul.style.display== " Block ") {OUl.style.display == "none ' ;} else{oul.style.display= = "block ; }}
But if we use the ternary operator, we might just need the following line of code:
obth.onclick=function() { OUl.style.display = = "Block"? oul.style.display= "None": oul.style.display= " Block "}
There is a magic wood. Of course, I just use a relatively easy to understand the wording, there is a lot of optimization space, we can certainly do this:
obth.onclick=function() { var style = OUl.style.display; oul.style.display= style = = "Block"? "None": "Block" // It must not be forgotten to re-assign the result to the element-- //oul.style.display= (style = = "Block")? "None": "block") more readable}
The above code means that if the style = = "Block" is established, it returns none, returns to block, and assigns the return result to the action element, but pay special attention to the usage and difference of = and = =. Because the assignment operator (=) has a lower precedence, the assignment operation is performed last. If you add the following ternary operator (), the readability will be a bit higher, but the effect is the same.
More error-prone places:
The more error-prone problem of ternary operations is the priority of the operation:
False; // return to $2.00
What is the cause of the error? The operation priority is lower than +, so the actual running statement is:
"Current Cost false"? "$2.00": "$10.00");
The string is true in JS, so it will output $2.00.
But to avoid the above mistakes, you can remember:
No false, 0, undefined, NaN, "" or null , JS thinks it is.true;
So the specific use of ternary operators or if else a matter of opinion, depending on the circumstances.
Thanks for reading!
JS three-dimensional expression