10 JavaScript Tips

Source: Internet
Author: User
Tags exit in

1. Variable conversions

It looks simple, but as far as I can see, using constructors, such as array () or number (), is a common practice for variable conversions. Always use raw data types (sometimes called literals) to convert variables, which is more efficient without any additional impact.

1 varMyVar = "3.14159",2 3str = "" + MyVar,//To string4 5 int= ~~myvar,//To integer6 7 float= 1*myvar,//To float8 9BOOL =!! MyVar,/*To Boolean-any string with lengthTen  One and any number except 0 is true*/ A  -Array = [MyVar];//to array

The conversion date (new Date (MyVar)) and the regular expression (new RegExp (MyVar)) must use the constructor, and when creating the regular expression, use the form/pattern/flags.

2. Decimal is converted to hexadecimal or octal, or vice versa

Do you write a separate function to convert hexadecimal (or octal)? Stop Right now! There are easier ready-made functions that can be used:

1 (int//  converts int to hex, eg + = "C"23 (int/ /  converts int to octal, eg. [+]45//  converts hex to int, eg. "FF" = 25567//  converts octal to int, eg. "+"

3. Play a number

In addition to the previous section, there are more techniques for dealing with numbers

 1  0xFF; //  Hex declaration, returns 255  2  3  020; //  octal declaration, returns  4  5  1e3; //  exponential, same as 1 * MATH.POW (10,3), returns  6  //  opposite with previous, returns 1E3  8  //  

4.Javascript Version Detection

Do you know which version of JavaScript your browser supports? If you don't know, go to Wikipedia and check out the JavaScript version table. For some reason, some features of the Javascript 1.7 version are not widely supported. However, most browsers support the features of version 1.8 and 1.8.1. (Note: All IE browsers (IE8 or older versions) only support version 1.5 JavaScript) Here is a script that detects the JavaScript version by detecting features, and it also checks the features supported by a particular JavaScript version.

varJs_ver =[];(Number.prototype.toFixed)? Js_ver.push ("1.5"):false;([].indexof&& [].foreach]? Js_ver.push ("1.6"):false;((function(){Try{[A, b] = [0,1];return true;}Catch(ex) {return false;}}) ())? Js_ver.push ("1.7"):false;([].reduce&& [].reduceright && JSON]? Js_ver.push ("1.8"):false;("". Trimleft)? Js_ver.push ("1.8.1"):false; Js_ver.supports=function() {if(arguments[0])return(!! ~ This. Join (). IndexOf (Arguments[0] + ",") + ","); Else      return( This[ This. length-1]);} Alert ("Latest Javascript version supported:" +js_ver.supports ()); Alert ("Support for version 1.7:" + js_ver.supports ("1.7"));

5. Use Window.name for simple session processing

This is something I really like. You can specify a string as the value of the Window.name property until you close the label or window. Although I did not provide any scripts, I strongly recommend that you take advantage of this approach. For example, it is useful to switch between debug and test mode when building a website or application.

6. Determine if a property exists

There are two aspects to this problem, both when checking the properties and getting the type of the property. But we always ignore the little things:

//Bad:this would cause an error in code if foo is undefinedif(foo) {dosomething ();}//good:this doesn ' t cause any errors. However, even when//Foo is set to NULL or false, the condition validates as trueif(typeofFoo! = "undefined") {dosomething ();}//better:this doesn ' t cause any errors and in addition//values NULL or false won ' t validate as Trueif(Window.foo) {dosomething ();}

However, there are situations where we have deeper structures and need more appropriate checks when you can:

1 // Ugly:we has to proof existence of every 2 3 // object before we can be sure property actually exists 4 5 if (Window.ofoo && ofoo.obar && oFoo.oBar.baz) {67  dosomething ();  89 }

7. Passing parameters to a function

When a function has both a required and optional parameter, we might do the following:

function dosomething (arg0, Arg1, arg2, Arg3, Arg4) {...} DoSomething (false);

Passing an object is always more convenient than passing a bunch of arguments:

1 functiondosomething () {2 3     //Leaves The function if nothing is passed4 5     if(!arguments[0]) {6 7     return false;8 9 }Ten  One     varOargs = Arguments[0] A  -arg0 = oargs.arg0 | | "", -  theArg1 = Oargs.arg1 | | "", -  -arg2 = Oargs.arg2 | | 0, -  +Arg3 = Oargs.arg3 | | [], -  +Arg4 = Oargs.arg4 | |false; A  at } -  - dosomething ({ -  -Arg1: "foo", -  inArg2:5, -  toARG4:false +  -});

This is just a simple example of passing an object as a parameter, for example, we can also declare an object, the variable name as the key, and the default value as value.

8. Using Document.createdocumentfragment ()

You may need to dynamically append multiple elements to the document. However, inserting them directly into the document will cause the document to need to be re-laid out one at a time, instead, you should use the document fragment and append only once when it is built:

1 functioncreatelist () {2 3     varALI = ["First item", "Second item", "Third item",4 5"Fourth item", "Fith item"];6 7     //creates the fragment8 9     varOfrag =document.createdocumentfragment ();Ten  One      while(ali.length) { A  -       varOLI = document.createelement ("li"); -  the       //removes the first item from array and appends it -  -       //As a text node to LI element -  + Oli.appendchild (document.createTextNode (Ali.shift ())); -  + Ofrag.appendchild (OLI); A  at } -  -document.getElementById (' Myul '). appendchild (Ofrag); -  -}

9. Passing a function to the replace () method

Sometimes when you want to replace a part of a string with another value, the best way is to pass a separate function to String.Replace (). Here is a simple example:

1 varSflop = "Flop: [Ah] [Ks] [7c]";2 3 varAvalues = {"A": "Ace", "K": "King", 7: "Seven"};4 5 varAsuits = {"H": "Hearts", "s": "Spades",6 7"D": "Diamonds", "C": "Clubs"};8 9Sflop = Sflop.replace (/\[\w+\]/gi,function(match) {Ten  OneMatch = Match.replace (match[2], asuits[match[2]]); A  -Match = Match.replace (match[1], avalues[match[1]] + "of"); -  the     returnmatch; -  - }); -  + //string Sflop now contains: -  + //"Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"

10. Use of labels in the loop

In some cases, loops are nested in loops, and you may want to exit in a loop, and you can use tags:

1 Outerloop:2 3  for(varii=0;ii<5;ii++) {4 5     if(Somethingistrue ()) {6 7     //Breaks The outer loop iteration8 9      BreakOuterloop;Ten  One } A  - Innerloop: -  the      for(varia=0;ia<5;ia++) { -  -       if(Somethingelseistrue ()) { -  +       //Breaks The inner loop iteration -  +        BreakInnerloop; A  at } -  - } -  -}

10 JavaScript Tips

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.