Simplified JavaScript Condition Statement

Source: Internet
Author: User

It is often used in many places.CodeSee many abbreviated conditional expression statements.Article, Think3WAYS2SAYIFThis article (http://www.thomasfrank.se/3_ways_2_say_if.html) is good. In this article, the traditional if... else ...,? :, &/| The characteristics and usage of the three expressions are summarized and summarized as follows:

1. If... else Structure

 //  Set R to 0 or 1  
VaR R = math. Floor (2 * Math. Random ())

// Set A, B and C to "small" If R = 0 an else set them to "big"
// Using three different techniques

// Method 1: If else
VaR A; If (R = 0) {A = "small "} Else {A = "big "};

// Method 2: Conditional Operator
VaR B = r = 0? "Small": "big ";

// Method 3: and/or operators
VaR C = r = 0 & "small" | "big ";

// Check the values of our Variables
Alert (R + "" + A + "" + B + "" + C );

2. If... else if... else Structure

 // Set R to 0, 1, 2 or 3  
VaR R = math. Floor (4 * Math. Random ())

// Set A, B and C to "nada", "small", "big" and "huge"
// Depending on the value or r using three different techniques

// Method 1: If... else if... else
VaR A;
If (R = 0) {A = "nada "}
Else If (R = 1) {A = "small "}
Else If (R = 2) {A = "big "}
Else {A = "huge "};

// Method 2: Conditional Operators
VaR B =
R = 0? "Nada"
: R = 1? "Small"
: R = 2? "Big"
: "Huge ";

// Method 3: and/or operators
VaR C =
R = 0 & "nada"
| R = 1 & "small"
| R = 2 & "big"
| "Huge ";

// Check the values of our Variables
Alert (R + "" + A + "" + B + "" + C );

3. Execute the Function

 //  Set R to 0, 1, 2 or 3  
VaR R = math. Floor (4 * Math. Random ())

// The global variable X and our four functions
VaR X = "";
Nada = Function () {X + = "nada! "};
Small = Function () {X + = "small! "};
Big = Function () {X + = "big! "};
Huge = Function () {X + = "huge! "};

// Call a specific function depending on the value of R
// Using three different techniques

// Method 1: If... else if... else
If (R = 0) {Nada ()}
Else If (R = 1) {small ()}
Else If (R = 2) {big ()}
Else {Huge ()};

// Method 2: Conditional Operators
R = 0? Nada ()
: R = 1? Small ()
: R = 2? Big ()
: Huge ();

// Method 3: and/or operators
R = 0 & (Nada () | True ) // The Nada () function does not necessarily return true. To ensure the subsequent logic or | the true value must be returned if the judgment is not executed.
| R = 1 & (small () | True )
| R = 2 & (big () | True )
| Huge ();

// Check the values of our Variables
Alert (R + "" + x );

4. Run the code

 //  Set R to 0, 1, 2 or 3  
VaR R = math. Floor (4 * Math. Random ())

// The global variable X
VaR X = "";

// Executing different code depending on the value of R
// Using three different techniques

// Method 1: If... else if... else
If (R = 0) {x + = "nada! "}
Else If (R = 1) {x + = "small! "}
Else If (R = 2) {x + = "big! "}
Else {X + = "huge! "};

// Method 2: Conditional Operators
R = 0? Function () {X + = "nada! "}()
: R = 1? Function () {X + = "small! "}()
: R = 2? Function () {X + = "big! "}()
: Function () {X + = "huge! "}();

// Method 3: and/or operators
R = 0 &&( Function () {X + = "nada! "} () | True )
// Some people pointed out in the comments that the anonymous function is not required. This is true when only one executable code exists. However, if multiple codes need to be executed, anonymous functions are good.
| R = 1 &&( Function () {X + = "small! "} () | True )
| R = 2 &&( Function () {X + = "big! "} () | True )
|Function () {X + = "huge! "}();

// Check the values of our Variables
Alert (R + "" + x );

In this article, the author focuses on whether the code is short or not. So in general, the author prefers to use the same function? : Operator, and think that the & | method requires more than a few letters, so it seems cumbersome. In the case of function execution, it is more convenient to use the traditional if... else. In its comments, some people suggested that the client-side code should be simpler and shorter, which would greatly improve some inconspicuous running efficiency.ProgramThis is also true. Therefore, selecting a more concise form of conditional statement processing may be more important than the running efficiency of these statements. Besides, the running efficiency may vary with UA.

If... else or? : They are both straightforward, and the & | calculation method is a little complicated. However, as long as you understand the following two basic principles, all problems will be solved:

1. When using logic and & and logic or | Operator, the direction is from left to right, & Operation stops when the first condition (or a value that can be converted to false, such as null/undefined/0/""/nan) is computed, the operation stops when the first condition (or value that can be converted to true) whose value is true; the value returned by the entire condition is the value of the final detection condition, not necessarily true/false.

Second, the logic has a higher priority than the & operator.

According to the first principle, r = 0 and "small" are calculated in the order from left to right. If R = 0 is true, "small" is detected ", "small" is a non-empty string, so the value of C is "small". If R = 0 is false, the system directly starts the logic or the second condition of | "big" detection, similarly, C should be set to "big ". According to the second principle, there is no need to add parentheses during the calculation of variable C in the above Code.

? : And &, | operator can play a role in streamlining code in a certain program.Source codeIs very important. To sum up, these operators are mainly applied in two aspects: assignment or return values, and Execution Code (for the time being, this classification ).

The usage of value assignment is everywhere in jquery or other libraries. A typical application is to implement the default value function for interfaces. We can easily write such code, for example:

VaRMyobj =Function(Options ){
VaRColor = options. color |This. Defaults. defaults;
VaRBackgroundcolor = options. backgroundcolor
|This. Defaults. backgroundcolor;
};
Myobj. Prototype. defaults = {
Color: & quot; #393939 & quot ",
Backgroundcolor: "#222"
}
VaRMyins =NewMyobj ({
Color: "#80ff80"
});
Console. Log ("color:" + myins. color + ", backgroundcolor:" + myins. backgroundcolor );

No use? : Or & |, because it does not have if... the inherent code block function of else (wrapped with {}), so they can only execute a single line of code, such:

 
(XMLHttpRequest. readystate = 4 & XMLHttpRequest. Status = 200 )? Alert ("success! "): Alert (" failure! ");

Therefore, if multiple codes need to be executed, anonymous functions should be used. For example:

 
(XMLHttpRequest. readystate = 4 & XMLHttpRequest. Status = 200 )?Function() {Alert ("success! ");VaRA = 100; alert (a) ;}: alert ("failure! ");

There are too many abbreviations in jquery 1.7.1 source code, such as line 2643:

 //  Hook for Boolean attributes  
Boolhook = {
Get: Function (ELEM, name ){
// Align Boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
VaR Attrnode,
Property = jquery. Prop (ELEM, name );
Return Property = True |
Typeof Property! = "Boolean" & (attrnode = ELEM. getattributenode (name) & attrnode. nodevalue! = False ?
Name. tolowercase ():
Undefined;
},
Set: function (){
...
}
}

It seems that you have to continue to learn and make a summary.

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.