JS in Trinocular operators and && | | Personal opinion of the character

Source: Internet
Author: User

These two days to see someone write code, feel very good, such as the next, the great god please ignore

$ (". Lgn"). On ("click",function() {        varA = {}; A.logintype= $( This). Data ("Logintype")); A.logintype= = Wx_utils. Login_type. Wx? (A.username = $ ("#username"). Val (), A.password = $ ("#password"). Val ()): A.logintype = = Wx_utils. Login_type. Ecard && (a.username = f | | $ ("#username_"). Val (), A.password = $ ("#password_"). Val (), A.customercode = d | | $ ("#c Ustomercode "). Val (), A.outid = $ (" #outid "). Val ()); A.scopes= []; $("Input[name= ' Scope_box ']:checked"). each (function(b, c) {A.scopes.push (C.value)}); Wx_utils.login (A,!1,function(a) {a&& 202102 = = A.errorcode? ($ (". Modal-overlay"). AddClass ("Modal-overlay-visible"), $ ("#bind_ecard_div"). Show ()): Wx_utils.toast (A)});

This is probably the case, the main logic in accordance with the three-mesh operator to write judgment

First, the trinocular operator,

Grammar

Conditions? STATEMENTA:STATEMENTB;

The above statement, first judge the condition condition, if the result is true to execute the statement Statementa, otherwise execute the statement statementb.
It is notable that the JavaScript script interpreter will be semicolon "; "As the Terminator of the statement, both the Statementa and the STATEMENTB statements must be single statements, and the use of multiple statements will give an error.

Generally we use this time, if Statementa or statementb inside a semicolon or comma, will be an error

var c = 1; c==1? Console.log (c), Console.log (' 1 '): Console.log (' C not equal to 1 ');

The result is uncaught syntaxerror:unexpected token, error.

So how do you output more statements or perform more than one operation?

Wrap the Statementa with parentheses, and you can execute multiple statements with a comma-delimited character.

var a = 5; function ABC () {    console.log (' I am method abc ')}function  err () {    console.log (' I am method err ') )}a==2? (ABC ()): Err (); a==5? (ABC (), ABC ()): Err ();

The results are as follows

I am the method err

I am the method abc

I am the method abc

Statementa or STATEMENTB inside can also put function oh.

Note that what is the difference between the trinocular operator and if else?

For n++;

var  n = 0; if (n >==0;} Else  ++ = 1;
var m = 0= M >= 10? m=0:m++= 0;

For ++n;

var  n = 0; if (n >==0;} Else {++ = 1;
var m = 0= M >= 10? M=0: ++ = 1;

n++ and ++n in this validation, there is no difference, because if else is the result of the calculation, does not return n, no return value

But for the trinocular operation, the n value returned by n++ is n itself, and the ++n returns the N value as the result after n+1

Again, logical operators.

A () && B (): performs B () and returns the value of B if it returns true after a () is executed, or False if a () is executed, the entire expression returns the value of a (), and B () does not execute;
A () | | B (): If you return true after a () is executed, the entire expression returns the value of a (), B () does not execute, and if A () returns false, B () is executed and the value of B () is returned;
&& priority is higher than | |

1, as long as "| |" False in front, regardless of "| |" Followed by true or FALSE, return "| |" The value that follows.

2, as long as "| |" Preceded by true, regardless of "| |" Followed by true or FALSE, return "| |" The preceding value.

3, as long as "&&" is false, whether "&&" followed by true or false, the result will be "&&" the preceding value;

4, as long as "&&" is true, whether "&&" followed by true or false, the result will be returned to "&&" the value after;

So, we can use && instead of if else to judge, for example, if we judge whether certain objects exist or if some variables are equal to a certain value, we can write a && a=5; A.length > 0 && $ ('. Login '). Show () This class.

As an example,


It is assumed that the growth rate is indicated as follows:
Growth rate of 5 shows 1 arrows;
Growth rate of 10 shows 2 arrows;
Growth rate of 12 shows 3 arrows;
Growth rate of 15 shows 4 arrows;
All other displays are displayed with 0 arrows.

Various methods at a glance

//if Else implementationvarAdd_level = 0; if(Add_step = = 5) {Add_level= 1; }Else if(Add_step = = 10) {Add_level= 2; }Else if(Add_step = = 12) {Add_level= 3; }Else if(Add_step = = 15) {Add_level= 4; }Else{add_level= 0; }
//You can also use switch to implementvarAdd_level = 0; Switch(add_step) { Case5: Add_level= 1;  Break;  Case10: Add_level= 2;  Break;  Case12: Add_level= 3;  Break;  Case15: Add_level= 4;  Break; default: Add_level= 0;  Break;}

If the demand changes to:
Growth speed of >12 display 4 arrows;
Growth speed of >10 display 3 arrows;
Growth speed of >5 display 2 arrows;
Growth speed of >0 display 1 arrows;
Growth Speed shows 0 arrows for <=0.

Then using switch to implement it is also very troublesome.


So have you ever thought of using a single line to implement the code?

Implement these 2 questions with logical operators

First question

// && | | Implementing var
// the more elegant way var
This method also see not quite understand, hope seniors see to me analysis under.

Second question

Var

First of all, let us comb a concept, you must remember: in the JS logic operation, 0, "", null, False, undefined, Nan will be sentenced to false, the others are true (as if there is no missing, please confirm below). This must be remembered, otherwise the application | | And && will have problems.
Here by the way: Often people ask me, see a lot of code if (!!). attr), why not write directly if (attr);
In fact, this is a more rigorous wording:
typeof 5 and typeof are tested below!! 5 the difference.!! The function is to convert a variable of another type to the bool type.

typeof 5 "number"typeof !! 5 "Boolean"

The following is the main discussion of logical operators && and | | |.
In almost all languages | | and && follow the principle of "short circuit" , such as the first expression in && is false to not handle the second expression, and | | Just the opposite.
JS also follows the above principles. But what's interesting is the value they return.

Here's an example of loading a child template in angularjs based on a role

<div ng-include= "user.admin&& ' edit.admin.html ' | | ' Edit.user.html ' "></div>

If User.admin is true, the second expression edit.admin.html is run, and the return value is the second expression, edit.admin.html

If User.admin is false, then user.admin&& ' edit.admin.html ' expression is false, go back to run | | After the third expression, the third expression is true, and the result is the value of the third expression.

Look at the simple point.

var true && 4 &&= AAA

Take a look again | | :

var attr = attr | | “”;

This operation is often used to determine whether a variable is defined, and if it is not defined, give him an initial value, which is useful when defining a default value for a function's parameters. Again remind you to remember the above principle: if the argument needs to be 0, "", null, False, undefined, Nan, it will also be false to handle.

if (a >=5) {   

This is done with a single line of code. But one of the points to note : JS | | And && features help us streamline the code while also bringing down the readability of the code. This needs to be weighed on our own.
On the one hand, the simplification of JS code, can substantially reduce network traffic, especially a large number of applications JS Common library. Personally, it is recommended that if it is a relatively complex application, please write some comments appropriately. This is the same as being an expression, able to streamline the code, but the readability will be reduced, the person who reads the code is higher, the best way is to write comments.

We can not use these techniques, but we must be able to understand, because these techniques have been widely used, especially like jquery, such as JS box code, do not understand these you will be difficult to understand the code of others.

Like

var yahoo = Yahoo | | {};

This is very widely used.
OK, let's take a look at the code in jquery:

varWrap =//option or Optgroup!tags.indexof ("<opt") &&     [ 1, "<select multiple= ' multiple ' >", "</select>" | | !tags.indexof ("<leg") &&     [ 1, "<fieldset>", "</fieldset>" | |Tags.match (/^< (THEAD|TBODY|TFOOT|COLG|CAP)/) &&     [ 1, "<table>", "</table>" | | !tags.indexof ("<tr") &&     [ 2, "<table><tbody>", "</tbody></table>" | |//<thead> matched above(!tags.indexof ("<td") | |!tags.indexof ("<th") &&     [ 3, "<table><tbody><tr>", "</tr></tbody></table>" | | !tags.indexof ("<col") &&     [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" | |//IE can ' t serialize <link> and <script> tags normally!jquery.support.htmlserialize &&     [ 1, "div<div>", "</div>" | |     [ 0, "", "" " ]; //Go to HTML and back, then peel off extra wrappersdiv.innerhtml = wrap[1] + elem + wrap[2]; //Move to the right depth     while(wrap[0]--) Div= Div.lastchild;

This code is used by the author to process $ (HTML), some tags must be constrained, such as <option> must be within the <select></select>.
Maybe you also found the author there is a very clever place is!tags.indexof ("<opt"), the author is very simple to realize the Startwith function, there is no redundant code. There are many such subtle codes in the jquery source code that you can learn from.

The second half of the content is reproduced from http://www.cnblogs.com/ppforever/p/4375996.html

JS in Trinocular operators and && | | Personal opinion of the character

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.