10 practical tips for JavaScript programming _javascript tips

Source: Internet
Author: User
Tags exit in

In this article, I'll list 10 JavaScript practical tips, primarily for JavaScript novices and mid-level developers. Hopefully, every reader can learn at least one useful skill.

1. Variable Conversion

It looks simple, but as far as I can see, using a constructor, like array () or number () for variable conversion is a common practice. Always use the original data type (sometimes called the literal amount) to convert the variable, which is more efficient without any additional impact.

Copy Code code 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 except 0 are true */
Array = [MyVar]; To array

The conversion date (new Date (MyVar)) and the regular expression (new RegExp (MyVar)) must use the constructor, and the form of the regular expression should be created using the/pattern/flags.

2. Decimal conversion to hexadecimal or octal, or vice versa

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

Copy Code code as follows:

(int). toString (16); converts int to hex, eg => "C"
(int). toString (8); converts int to octal, eg. => "14"
parseint (string,16)//converts hex to int, eg. "FF" => 255
parseint (string,8)//converts octal to int, eg. "=>" 16

3. Play Digital

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

Copy Code code as follows:

0xFF; Hex declaration, returns 255
020; Octal declaration, returns 16
1E3; Exponential, same as 1 * MATH.POW (10,3), returns 1000
(1000). 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 of the table. For some reason, some of the features of the Javascript 1.7 version are not widely supported. However, most browsers support the features of version 1.8 and version 1.8.1. (Note: All IE browsers (IE8 or older versions) support only version 1.5 JavaScript) Here's a script that detects JavaScript versions by detecting features, and it checks for features supported by specific JavaScript versions.

Copy Code code 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 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 do not provide any scripts, I strongly recommend that you take full advantage of this method. For example, when building a Web site or application, it is useful to switch between debugging and test mode.

6. Determine whether a property exists

This problem includes two aspects, both when checking properties and getting the type of the property. But we always ignore these little things:

Copy Code code as follows:

Bad:this would 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 ();
}

But, in some cases, we have deeper structures and need more appropriate checks when it can:
Copy Code code as follows:
Ugly: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 function

We might do this when the function has both the required and optional parameters:
Copy Code code as follows:
function dosomething (arg0, Arg1, arg2, Arg3, Arg4) {
...
}
DoSomething (', ' foo ', 5, [], false);

Passing an object is always more convenient than passing a bunch of arguments:
Copy Code code as follows:
function dosomething () {
Leaves the function if it 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 also declare an object, the variable name as key, and the default value as value.

8. Use of 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 be redesigned one at a time, instead, you should use the document fragment and append it only once:

Copy Code code as follows:
function CreateList () {
var ALI = ["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 "I" 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 a string with another value, and the best way to do that is to pass a separate function to String.Replace (). Here is a simple example:

Copy Code code 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]] + "of");
return match;
});
String Sflop now contains:
"Flop: [Ace of Hearts] [King of Spades] [Seven of clubs]"


10. Use of labels in circulation

There are times when loops are nested in loops, and you may want to exit in a loop, you can use the tag:

Copy Code code 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;
}
}
}

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.