10 tips on JavaScript that you may not know

Source: Internet
Author: User
Tags exit in

Although I have been using JavaScript for development for many years, it often has some small features that surprised me. For me, JavaScript requires continuous learning. In this articleArticleI 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 (sometimes called the literal volume) to convert the variable, which is more efficient without any additional impact.

1234567 var myvar = "3.14159" , STR = "" + myvar, // to string Int = ~~ Myvar, // to integer float = 1 * myvar, // to float bool = !! Myvar, /* to Boolean-any string with length and any number limit T 0 are true */ 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 to use:

1234 (INT). tostring (16 );// Converts int to hex, eg 12 => "C"(INT). tostring (8 );// Converts int to octal, eg. 12 => "14"Parseint (string, 16)// Converts hex to int, eg. "FF" => 255Parseint (string, 8)// Converts octal to int, eg. "20" => 16
3. Play with numbers

In addition to the previous section, there are more techniques to process numbers.

12345 0xff;// Hex declaration, returns 255020;// Octal declaration, returns 161e3;// Exponential, same as 1 * Math. Pow (1000), returns(1000). toexponential ();// Opposite with previous, returns 1e3(3.1415). tofixed (3 );// Rounding the number and 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 ie browsers (IE8 or older versions) only support JavaScript of 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.

123456789101112131415 VaR Js_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 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, when building a website or applicationProgramIt is very useful to switch between the debugging and testing modes.

6. determine whether an attribute exists

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

1234567891011121314 // Bad: this will cause an error in code when foo is undefined If (FOO ){ Dosomething (); } // Good: This doesn' t cause any errors. However, even when // Foo is set to null or false, the condition validates as true If ( Typeof Foo! = "Undefined" ){ Dosomething (); } // Better: This doesn't cause any errors and in addition // Values null or false won't validate as true If (Window. Foo ){ Dosomething (); }

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

12345 // Uugly: We have to proof existence of every// Object before we can be sure property actually existsIf (Window. ofoo & ofoo. obar & ofoo. obar. BAZ ){Dosomething ();}
7. Pass parameters to the Function

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

1234 Function Dosomething (arg0, arg1, arg2, arg3, arg4 ){...}Dosomething ('','Foo', 5, [],False);

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

1234567891011121314151617 Function Dosomething (){ // Leaves the function if nothing is passed If (! Arguments [0]) { Return False ; } VaR Oargs = arguments [0] Arg0 = oargs. arg0 | "" , Arg1 = oargs. arg1 | "" , Arg2 = oargs. arg2 | 0, Arg3 = oargs. arg3 | [], Arg4 = oargs. arg4 | False ; } Dosomething ({ Arg1: "Foo" , Arg2: 5, Arg4: False });

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:

1234567891011121314 Function Createlist (){ VaR Ali = [ "First item" , "Second item" , "Third item" , "Fourth item" , "Fith item" ]; // Creates the fragment VaR Ofrag = Document. createdocumentfragment (); While (Ali. Length ){ VaR Oli = Document. createelement ( "Li" ); // 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 ); } Document. getelementbyid ( 'Myul' ). Appendchild (ofrag ); }
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. The following is a simple example:

1234567891011 VaR Sflop = "Flop: [Ah] [Ks] [7C]" ; VaR Avalues = { "" : "Ace" , "K" : "King" , 7: "Seven" }; VaR Asuits = { "H" : "Hearts" , "S" : "Spades" , "D" : "Diamonds" , "C" : "Clubs" }; Sflop = sflop. Replace (/\ [\ W + \]/GI, Function (MATCH ){ Match = match. Replace (Match [2], asuits [Match [2]); Match = match. Replace (Match [1], avalues [Match [1] + "" ); Return Match; }); // String sflop now contains: // "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:

1234567891011121314 Outerloop: For ( VaR II = 0; II <5; II ++ ){ If (Somethingistrue ()){ // Breaks the outer loop iteration Break Outerloop; } Innerloop: For ( VaR IA = 0; IA <5; IA ++ ){ If (Somethingelseistrue ()){ // Breaks the inner loop iteration Break Innerloop; } } }
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.