Experience Sharing: Tips on JavaScript

Source: Internet
Author: User
Tags exit in

Although I useJavascriptI have been doing development for many years, but it often has some small features that surprised me. For me, Javascript requires continuous learning. In this article, I will list 10 tips for using Javascript, mainly for beginners and intermediate developers of Javascript. I hope every reader can learn at least one useful technique.

1. Variable Conversion

It looks simple, but as I can see, using constructors such as Array () or Number () for variable conversion is a common practice. Always use the original data type (also called literal) to convert the variable, which is more efficient without any additional impact. Www.phperz.com

 
 
  1. varmyVar ="3.14159",  
  2. str =""+ myVar,// to string  
  3. int= ~~myVar,// to integer  
  4. float= 1*myVar,// to float  
  5. bool = !!myVar,/* to boolean - any string with length  
  6. and any number except 0 are true */ 
  7. array = [myVar];// to array  

The new Date (myVar) and regular expression (new RegExp (myVar) must use constructors and use the/pattern/flags format when creating regular expressions.

2. Convert decimal to hexadecimal or octal, or vice versa.

Do you want to write a separate function to convert hexadecimal or octal? Stop now! There are more easily available functions available: PHP programmer site

 
 
  1. (int).toString(16);// converts int to hex, eg 12 => "C"  
  2. (int).toString(8);// converts int to octal, eg. 12 => "14"  
  3. parseInt(string,16)// converts hex to int, eg. "FF" => 255  
  4. parseInt(string,8)// converts octal to int, eg. "20" => 16  

3. Play with numbers

In addition to the previous section, here are more tips for dealing with numbers: www.phperz.com

 
 
  1. 0xFF;// Hex declaration, returns 255  
  2. 020;// Octal declaration, returns 16  
  3. 1e3;// Exponential, same as 1 * Math.pow(10,3), returns 1000  
  4. (1000).toExponential();// Opposite with previous, returns 1e3  
  5. (3.1415).toFixed(3);// Rounding the number, returns "3.142"  

4. Javascript version check

Do you know which version of Javascript your browser supports? If you do not know, go to Wikipedia to check the Javascript version table. For some reason, some features of Javascript 1.7 are not widely supported. However, most browsers support the features of version 1.8 and 1.8.1. Note: All Internet Explorer IE8 or older versions) only support Javascript version 1.5. Here is a script that can detect the JavaScript version by detecting features, it can also check the features supported by specific Javascript versions.

 
 
  1. varJS_ver = [];  
  2. (Number.prototype.toFixed)?JS_ver.push("1.5"):false;  
  3. ([].indexOf && [].forEach)?JS_ver.push("1.6"):false;  
  4. ((function(){try{[a,b] = [0,1];returntrue;}catch(ex) {returnfalse;}})())?JS_ver.push("1.7"):false;  
  5. ([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;  
  6. ("".trimLeft)?JS_ver.push("1.8.1"):false;  
  7. JS_ver.supports =function()  
  8. {  
  9. if(arguments[0])  
  10. return(!!~this.join().indexOf(arguments[0] +",") +",");  
  11. else 
  12. return(this[this.length-1]);  
  13. }  
  14. alert("Latest Javascript version supported: "+ JS_ver.supports());  
  15. alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));  

5. Use window. name for simple session Processing

This is what I really like. You can specify a string as the value of the window. name attribute until you close the tag or window. Although I have not provided any scripts, I strongly recommend that you make full use of this method. For example, switching between debugging and testing modes is very useful when building a website or application.

6. determine whether an attribute exists

This issue involves two aspects: Checking attributes and obtaining attribute types. However, we always ignore these small things:

 
 
  1. // BAD: This will cause an error in code when foo is undefined    
  2.  www.phperz.com  if(foo)   
  3. {  doSomething();  }    
  4. // GOOD: This doesn't cause any errors. However, even when  
  5. // foo is set to NULL or false, the condition validates as trueif(typeoffoo !="undefined")   
  6. {doSomething();} down.phperz.com  
  7. // BETTER: This doesn't cause any errors and in addition  
  8. // values NULL or false won't validate as trueif(window.foo)   
  9. {doSomething();} 

However, in some cases, when we have a deeper structure and need a more appropriate check, we can do this:

 
 
  1. // UGLY: we have to proof existence of every  
  2. // object before we can be sure property actually exists  
  3. if(window.oFoo && oFoo.oBar && oFoo.oBar.baz) {  
  4. doSomething();  
  5. }  

7. Pass parameters to the Function

When a function has both required and optional parameters, we may do this:

 
 
  1. functiondoSomething(arg0, arg1, arg2, arg3, arg4) {  
  2. ...  
  3. }  
  4. doSomething('','foo', 5, [],false);  

Passing an object is always easier than passing a bunch of parameters:

 
 
  1. functiondoSomething() {  
  2. // Leaves the function if nothing is passed  
  3. if(!arguments[0]) {  
  4. returnfalse;  
  5. }  
  6. varoArgs = arguments[0]  
  7. arg0 = oArgs.arg0 ||"",  
  8. arg1 = oArgs.arg1 ||"",  
  9. arg2 = oArgs.arg2 || 0,  
  10. arg3 = oArgs.arg3 || [],  
  11. arg4 = oArgs.arg4 ||false;   
  12. }   
  13. doSomething({  
  14. arg1 :"foo",  
  15. arg2 : 5,  
  16. arg4 :false 
  17. });  

This is just a simple example of passing an object as a parameter. For example, we can declare an object, the variable name as the Key, and the default Value as the Value.

8. Use document. createDocumentFragment ()

You may need to dynamically append multiple elements to the document. However, inserting them directly into the document will cause this document to be re-deployed each time. On the contrary, you should use the document fragments and add them only once after they are built:

 
 
  1. FunctiondoSomething (arg0, arg1, arg2, arg3, arg4 ){
  2. ...
  3. }
  4. DoSomething ('', 'foo', 5, [], false );
  5. Passing an object is always easier than passing a bunch of parameters:
  6. FunctioncreateList (){
  7. VaraLI = ["first item", "second item", "third item", "fourth item", "fith item"];
  8. // Creates the fragment
  9. VaroFrag = document. createDocumentFragment ();
  10. While (aLI. length ){
  11. VaroLI = document. createElement ("li ");
  12. // Removes the first item from array and appends it
  13. // As a text node to LIelement
  14. OLI. appendChild (document. createTextNode (aLI. shift ()));
  15. OFrag. appendChild (oLI );
  16. }
  17. Document. getElementById ('myul '). appendChild (oFrag );
  18. }

9. Pass a function for the replace () method

Sometimes you want to replace a part of the String with other values. The best way is to pass an independent function to String. replace. PHP programmer site

The following is a simple example of achieving massive output in online poker games:

 
 
  1. varsFlop ="Flop: [Ah] [Ks] [7c]";  
  2. varaValues = {"A":"Ace","K":"King",7:"Seven"};  
  3. varaSuits = {"h":"Hearts","s":"Spades","d":"Diamonds","c":"Clubs"};  
  4. sFlop = sFlop.replace(/\[\w+\]/gi,function(match) {  
  5. match = match.replace(match[2], aSuits[match[2]]);  
  6. match = match.replace(match[1], aValues[match[1]] +" of ");  
  7. returnmatch;  
  8. });  
  9. // string sFlop now contains:  
  10. // "Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"  

10. Use of tags in a loop

Sometimes, a loop is nested in the loop. If you want to exit in the loop, you can use the tag:

 
 
  1. outerloop:  
  2. for(variI=0;iI<5;iI++) {  
  3. if(somethingIsTrue()) {  
  4. // Breaks the outer loop iteration  
  5. breakouterloop;  
  6. }  
  7. innerloop:  
  8. for(variA=0;iA<5;iA++) {  
  9. if(somethingElseIsTrue()) {  
  10. // Breaks the inner loop iteration  
  11. breakinnerloop;  
  12. }  
  13. }  
  14. }  

We hope that the above content will help you.

Related Article

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.