Talk about how to develop JavaScript efficiently

Source: Internet
Author: User

Intermediary transaction http://www.aliyun.com/zixun/aggregation/6858.html ">seo diagnose Taobao guest cloud host technology Hall

Simplified code

With a shorter wording, not only can you reduce the number of characters you enter, but you can also reduce the file size. Most of the code that uses simple coding, the efficiency of implementation is slightly improved.

1.1 Simplifying Common object definitions:

Use var obj = {}; instead of var obj = new Object ();

Use var arr = []; instead of var arr = new Array ();

1.2 Streamlined if statement

The ternary operator can effectively streamline an if statement that involves only assignment-value operations, such as

var score = grade;

If (Score < 60) {

Grade = "Fail";

else {

Grade = "Pass";

}

Can be streamlined to:

var score = 60;

var grade = Score < 60? "Fail": "Pass";

The ternary operator also supports nesting, but too many nesting levels can affect the readability of the program.

1.3 Using JSON

JSON is a lightweight data format, and lightweight is first embodied in its very simple structure definition.

var obj = {};

OBJ.P1 = ' a ';

OBJ.P2 = ' B ';

OBJ.P3 = ' C ';

Can be streamlined to:

var obj = {

P1: ' A ',

P2: ' B ',

P3: ' C '

};

Second, the use of efficient code

There are a lot of efficiency optimization articles circulated on the Internet, and some of the more professional JavaScript books have been talked about, so here are just a few things to talk about.

2.1 Streamline Circulation body

The efficiency of a loop is largely determined by the loop body, and the difference between a for or a while is too small. Consider the following code that adds an event to a group of elements:

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 time the loop executes, it determines whether the attachevent or AddEventListener of the window object exists, but it is enough to judge once; In addition, the string concatenation of "" on "+ EventName" is repeated. The optimization 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 custom functions

When you perform an operation on a JavaScript built-in type variable, you should first check to see if the operation has a native method.

What would you do to generate a copy of an array? It seems to be the only way to iterate through an array element and then assign it to another array. In fact, the original Array.prototype.slice can achieve the purpose of replication. This method can return the selected element from an array without affecting the original array. If the argument is left blank, all the elements are returned.

Array.prototype.slice can also operate on types that are not arrays and that can be accessed through numeric indexes, such as arguments:

function Test () {

Alert (Array.prototype.slice.call (arguments));

}

Test (1, 2, 3); Output "1,2,3″

Under Firefox, it can even operate on htmlcollection. Unfortunately, not in IE.

Another example is array ordering, in general, we do not need to write another sorting algorithm, with native Array.prototype.sort is enough. The sort method has only one parameter, which is a function that determines which of the two elements of comparison are sorted by character order, such as 11 will be ranked before 2. To sort by number size, you can write this:

var arr = [11, 2, 0, 12, 33];

Arr.sort (

function (A, b) {

return b;

}

);

You can also sort by an attribute of an object:

var arr = [

{id:11},

{id:0},

{id:22}

];

Arr.sort (

function (A, b) {

return a.id-b.id;

}

);

2.3 Arrays to repeat

The array type does not provide a way to repeat, if you want to kill the repeating elements of the array, you have to do it yourself:

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 overall idea is to move the elements of the array to another array, the process of handling to check whether the element is duplicated, if there is a direct throw away. It can be seen from nested loops that this method is extremely inefficient. We can use a Hashtable structure to record existing elements so that we can avoid inner loops. Exactly, implementing Hashtable in JavaScript is extremely simple, 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;

}

Third, make the code easier to read, better maintenance

Keeping your code clear and readable can modify your code faster and more accurately, both in development and after development.

3.1 Connection HTML string

Believe that the front-end development of friends are suffering from this torture: when connecting HTML by the hateful single quotes, double quotes get dizzy. Like what:

element.innerhtml = ' + text + ';

This describes a string formatting function:

String.Format = function (str) {

var args = arguments, re = new RegExp ("% ([1-" + Args.length + "])", "G");

return String (str). replace (

Re,

Function ($) {

return args[$2];

}

);

};

Calling the method is simple:

element.innerhtml = String.Format ('%3 ', URL, msg, text);

The meaning is to replace the%n with the nth parameter. So much clearer.

3.2 Create a config configuration object for your program

When writing Java or C # programs, we typically read the program's configuration information from XML. In JavaScript, the configuration information in XML is not cost-effective, on the one hand to request an XML file or XML string into XML objects, on the other hand, the method of XML objects is more complex and lengthy. Lightweight JSON is the best choice.

Constants in your program should be placed in config configuration objects, such as URLs for AJAX requests, hints for an action, and so on, such as:

var Config = {

Ajaxurl: "Test.jsp",

Successtips: "Request Complete"

};

If the number of config is large, you can nest one layer based on the configuration type, such as:

var Config = {

URL: {

SRC1: "Test1.jsp",

SRC2: "Test2.jsp",

.

.

},

Tips: {

SRC1SUC: "Request 1 Complete",

SRC2SUC: "Request 2 Complete",

.

.

}

};

Config should be placed at the front of the program for easy viewing and modification.

Article source: http://bbs.seuuo.com/html/13/category-catid-13.html

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.