Javascript code can also be improved.

Source: Internet
Author: User

I. Simplified code
Using a shorter statement can not only reduce the number of characters entered, but also reduce the file size. The execution efficiency of most code that adopts simple writing is slightly improved.
1.1 simplify definition of common objects: use var obj ={} instead of var obj = new Object ();
Use var arr = []; instead of var arr = new Array ();
1.2 simplified if statement the ternary operator can effectively streamline the if statement that only involves the value transfer operation, such
Var score = 60, grade;
If (score <60 ){
Grade = "fail ";
} Else {
Grade = "pass ";
}
It can be simplified:
Var score = 60;
Var grade = score <60? "Fail": "pass ";
The ternary operators also support nesting, but too many layers of nesting will affect the readability of the program, which requires more consideration.
1.3 using JSONJSON is a lightweight data format. lightweight data is first reflected in its simple structure definition.
Var obj = {};
Obj. p1 = 'a ';
Obj. p2 = 'B ';
Obj. p3 = 'C ';
It can be simplified:
Var obj = {
P1: 'A ',
P2: 'B ',
P3: 'C'
};
Ii. Use efficient code
There are a lot of efficiency optimization articles circulating on the Internet, and some professional Javascript books have also talked about a lot. Therefore, we will only list some of the articles that are rarely mentioned here.
2.1 The efficiency of a streamlined loop is largely determined by the loop body. The difference between the for and while statements is too small. Consider the following code. Its function is to add events to a batch of elements:
Copy codeThe Code is as follows:
Function addEvent (elems, eventName, handler ){
For (var I = 0, len = elems. length; I <len; I ++ ){
If (window. attachEvent ){
Elems [I]. attachEvent ("on" + eventName, handler );
} Else if (window. addEventListener ){
Elems [I]. addEventListener (eventName, handler, false );
}
}
}

Every execution of a loop will judge whether the attachEvent or addEventListener of the window object exists. In fact, it is enough to judge only once. In addition, the String concatenation of "" on "+ eventName" is also executed repeatedly. The optimization is as follows:
Copy codeThe Code is as follows:
Function addEvent (elems, eventName, handler ){
Var I =-1, len = elems. length;
If (window. attachEvent ){
EventName = "on" + eventName;
While (++ I <len ){
Elems [I]. attachEvent (eventName, handler );
}
} Else if (window. addEventListener ){
While (++ I <len ){
Elems [I]. addEventListener (eventName, handler, false );
}
}
}

2.2 try to use native functions instead of user-defined functions. When you perform an operation on a Javascript built-in type variable, you should first check whether this operation has a native method.
What do you do to generate a copy of an array? Traversing array elements and assigning values to another array one by one seems to be the only method. In fact, native Array. prototype. slice can achieve the purpose of replication. This method returns selected elements from an array without affecting the original array. If the parameter is left blank, all elements are returned.
Array. prototype. slice can also operate on some types that are not arrays but can be accessed through digital indexes, suchCopy codeThe Code is as follows:
Arguments:
Arguments:
Function test (){
Alert (Array. prototype. slice. call (arguments ));
}
Test (1, 2, 3); // output "1, 2, 3 ″

In Firefox, it can even operate HtmlCollection. Unfortunately, it cannot be done in IE.
Another example is Array sorting. In general, we do not need to write another sorting algorithm. It is enough to use native Array. prototype. sort. The sort method has only one parameter. this parameter is a function that determines who is in the first place of the two elements. By default, the two elements are sorted in character order. For example, 11 is ranked before 2. To sort by number, you can write as follows:
Copy codeThe Code is as follows:
Var arr = [11, 2, 0, 12, 33];
Arr. sort (
Function (a, B ){
Return a-B;
}
);

You can also sort by an object attribute:
Copy codeThe Code is as follows:
Var arr = [
{Id: 11 },
{Id: 0 },
{Id: 22}
];
Arr. sort (
Function (a, B ){
Return a. id-B. id;
}
);

2.3 The Array deduplication method is not provided for the Array type. If you want to remove the repeated elements of the Array, you have to find a solution:
Copy codeThe Code is as follows:
Function unique (arr ){
Var result = [], isRepeated;
For (var I = 0, len = arr. length; I <len; I ++ ){
IsRepeated = false;
For (var j = 0, len = result. length; j <len; j ++ ){
If (arr [I] = result [j]) {
IsRepeated = true;
Break;
}
}
If (! IsRepeated ){
Result. push (arr [I]);
}
}
Return result;
}

The general idea is to move the array elements one by one to another. During the handling process, check whether there are duplicates of the elements. If so, the elements are discarded directly. From nested loops, we can see that this method is very inefficient. We can use a hashtable structure to record existing elements, so as to avoid inner loops. Exactly, implementing hashtable in Javascript is extremely simple, and the improvements are as follows:
Copy codeThe Code is as follows:
Function unique (arr ){
Var result = [], hash = {};
For (var I = 0, elem; (elem = arr [I])! = Null; I ++ ){
If (! Hash [elem]) {
Result. push (elem );
Hash [elem] = true;
}
}
Return result;
}

3. Make the code easier to read and maintain
Whether in development or after development, you can modify the code faster and more accurately by keeping the code clear and easy to read.
3.1 connecting HTML strings I believe all of my friends who are doing front-end development have suffered this torment: when connecting HTML, they are overwhelmed by hateful single quotes and double quotes. For example:
Element. innerHTML = ''+ text + '';
Here is a string Formatting Function:
Copy codeThe Code is as follows:
String. format = function (str ){
Var args = arguments, re = new RegExp ("% ([1-" + args. length + "])", "g ");
Return String (str). replace (
Re,
Function ($1, $2 ){
Return args [$2];
}
);
};

The call method is simple:
Copy codeThe Code is as follows:
Element. innerHTML = String. format ('% 3', url, msg, text );

Replace % n with the nth parameter. This is much clearer.
3.2 when creating a Config configuration object for your program to write Java or C # programs, we generally read the configuration information of the program from XML. In Javascript, it is not very cost-effective to use XML for configuration information. On the one hand, it is necessary to request an XML file or convert the XML string to an XML object. On the other hand, the XML Object method is complicated and lengthy. Lightweight JSON is the best choice.
Constants in the program should be placed in the Config configuration object, such as the Url of the Ajax request and the prompt of an operation. For example:
Copy codeThe Code is as follows:
Var Config = {
AjaxUrl: "test. jsp ",
SuccessTips: "request completed"
};

If the number of configurations is large, you can nest multiple layers based on the configuration type, for example:
Copy codeThe Code is as follows:
Var Config = {
Url :{
Src1: "test1.jsp ",
Src2: "test2.jsp ",
.
.
},
Tips :{
Src1Suc: "request 1 completed ",
Src2Suc: "request 2 completed ",
.
.
}
};
Config should be placed at the beginning of the Program for easy viewing and modification.

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.