Abbreviated Javascript Condition Statement (recommended) and short javascript statement

Source: Internet
Author: User

Abbreviated Javascript Condition Statement (recommended) and short javascript statement

Many abbreviated conditional expression statements are often seen in the code of cool people everywhere. After reading some articles about this, I think3 ways 2 say ifThis 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 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 funur 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) // nada () the function does not necessarily return true. To ensure the subsequent logic or | the judgment is not executed, the true value must be returned, the same below | 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) // someone pointed out in the comment that the anonymous function is not required. This is true when only one executable code exists, however, if multiple codes need to be executed, the anonymous function is still 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. Some people mentioned in their comments that it is correct to make the Client code more concise and short, and to improve some inconspicuous running efficiency. 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 &, | operators can play a role in streamlining code in a certain program. They are very important in Library Source Code such as jQuery. 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:

var myObj = function(options) {  var color = options.color || this.defaults.defaults;  var backgroundColor = options.backgroundColor      || this.defaults.backgroundColor;};myObj.prototype.defaults = {  color : "#393939",  backgroundColor : "#222"}var myIns = new myObj({  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!"); var a=100; alert(a);}: alert("Failure!");

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

// Hook for boolean attributesboolHook = {  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.

The preceding simplified Javascript Condition Statement (recommended) is all the content shared by the editor. I hope it can be used as a reference and support for the customer's home.

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.