JavaScript Conversion Tips

Source: Internet
Author: User
Tags exit in

1variable conversions look simple, but as far as I can see, it's common practice to use constructors, such as array () or number () to convert variables. Always use raw data types (sometimes called literals) to convert variables, which is more efficient without any additional impact. varMyVar = "3.14159", str= "" + MyVar,//To stringint= ~~myvar,//To integerfloat= 1*myvar,//To floatBOOL =!! MyVar,/*To Boolean-any string with lengthand any number except 0 is true*/Array= [MyVar];//to arrayConversion date (NewDate (MyVar)) and regular Expressions (NewREGEXP (MyVar)) must use constructors, and when creating regular expressions, use/pattern/the form of the flags. 2. Decimal is converted to hexadecimal or octal, or conversely do you write a separate function to convert hexadecimal (or octal)? Stop Right now! There are easier ready-made functions that can be used: (int). toString (16);//converts int to hex, eg, "C"(int). toString (8);//converts int to octal, eg.parseint (string,16)//converts hex to int, eg. "FF" = 255parseint (string,8)//converts octal to int, eg. "+"3. Play a number in addition to the previous section, there are more techniques for handling numbers0xFF;//Hex declaration, returns 255020;//octal declaration, returns1E3;//exponential, same as 1 * MATH.POW (10,3), returns(+). toexponential ();//opposite with Previous, returns 1E3(3.1415). toFixed (3);//rounding the number, returns "3.142"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, JavascriptSome features of version 1.7 are not widely supported. Most browsers, however, support version 1.8 and 1.8.. Version 1 features. (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. Using 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. 6the question of whether a property exists is a two-part problem, which includes 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://Ugly:we has to proof existence of every//object before we can be sure property actually existsif(Window.ofoo && Ofoo.obar &&OFoo.oBar.baz) {dosomething ();}7. Passing parameters to a function when a function has both a required and optional parameter, we might do the following:functiondosomething (arg0, Arg1, arg2, Arg3, Arg4) {...} DoSomething (', ' foo ', 5, [],false), passing an object is always more convenient than passing a bunch of arguments:functiondosomething () {//Leaves The function if nothing is passed    if(!arguments[0]) {return false; }varOargs = 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 also declare an object, the variable name as the key, and the default value as value. 8using 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:functioncreatelist () {varALI = ["First item", "Second item", "Third item","Fourth item", "Fith item"]; //creates the fragment    varOfrag =document.createdocumentfragment ();  while(ali.length) {varOLI = document.createelement ("li"); //removes the first item from array and appends it      //As a text node to LI elementOli.appendchild (document.createTextNode (Ali.shift ()));  Ofrag.appendchild (OLI); } document.getElementById (' Myul '). appendchild (Ofrag);}9. Passing a function for the replace () method sometimes 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:varSflop = "Flop: [Ah] [Ks] [7c]";varAvalues = {"A": "Ace", "K": "King", 7: "Seven"};varAsuits = {"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]] + "of"); returnmatch;});//string Sflop now contains://"Flop: [Ace of Hearts] [King of Spades] [Seven of Clubs]"10the use of labels in loops sometimes, loops are nested in loops, and you may want to exit in a loop, you can use the tag: Outerloop: for(varii=0;ii<5;ii++) {if(Somethingistrue ()) {//Breaks The outer loop iteration     BreakOuterloop; } Innerloop: for(varia=0;ia<5;ia++) {if(Somethingelseistrue ()) {//Breaks The inner loop iteration       BreakInnerloop; }}}

JavaScript Conversion Tips

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.