10 practical tips for JavaScript programming _ javascript skills

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 article, I will list 10 practical tips for 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.

The Code is as follows:

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 between 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:

The Code is as follows:


(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" => 255
ParseInt (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.

The Code is as follows:


0xFF; // Hex declaration, returns 255
020; // Octal declaration, returns 16
1e3; // Exponential, same as 1 * Math. pow (1000), returns
(1000). toExponential (); // Opposite with previous, returns 1e3
(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 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.

The Code is as follows:


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, 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:

The Code is as follows:


// 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:

The Code is as follows:

// Uugly: we have to proof existence of every
// Object before we can be sure property actually exists
If (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:

The Code is as follows:

Function doSomething (arg0, arg1, arg2, arg3, arg4 ){
...
}
DoSomething ('', 'foo', 5, [], false );


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

The Code is as follows:

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:

The Code is as follows:

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:

The Code is as follows:


Var sFlop = "Flop: [Ah] [Ks] [7c]";
Var aValues = {"A": "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:

The Code is as follows:


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;
}
}
}

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.