Javascript code can also be a graceful way to implement _javascript techniques

Source: Internet
Author: User
First, simplify the 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 is simple to use, the efficiency of implementation has been slightly improved.
1.1 Simplifying common object definitions: using var obj = {}; instead of var obj = new Object ();
Use var arr = []; instead of var arr = new Array ();
The 1.2 simplified if statement 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 Jsonjson is a lightweight data format, the lightweight first embodied in its structural definition is very simple.
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 The efficiency of a streamlined loop body cycle 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:
Copy Code code 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 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:
Copy Code code 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
Copy Code code as follows:

Arguments
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 a different 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:
Copy Code code as follows:

var arr = [11, 2, 0, 12, 33];
Arr.sort (
function (A, b) {
return a-b;
}
);

You can also sort by an attribute of an object:
Copy Code code as follows:

var arr = [
{id:11},
{id:0},
{id:22}
];
Arr.sort (
function (A, b) {
return a.id-b.id;
}
);

2.3 Array to repeat the array type does not provide a way to repeat, if you want to kill the repeated elements of the array, you have to find ways to:
Copy Code code 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 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 the inner loops can be avoided. Exactly, implementing Hashtable in JavaScript is extremely simple, as follows:
Copy Code code 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 Connecting HTML strings It is believed that friends who do front-end development have suffered this torment: when connecting HTML, they are confused by hateful single quotes and double quotes. Like what:
element.innerhtml = ' + text + ';
This describes a string formatting function:
Copy Code code as follows:

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:
Copy Code code as follows:

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

The meaning is to replace the%n with the nth parameter. It's a lot clearer.
3.2 When creating a config configuration object for your program to write 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 the Config configuration object, such as the URL of an AJAX request, a hint of an action, and so on, such as:
Copy Code code as follows:

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:
Copy Code code as follows:

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.

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.