Home > Web Front-end > JS Tutorial > Javascript code can also become beautiful implementation method_javascript skills

Javascript code can also become beautiful implementation method_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 18:51:14
Original
928 people have browsed it
1. Simplify the code
Using a shorter writing method can not only reduce the number of characters entered, but also reduce the file size. Most of the code written in a simple way has a slight improvement in execution efficiency.
1.1 Simplify common object definitions: use var obj = {}; instead of var obj = new Object();
Use var arr = []; instead of var arr = new Array();
1.2 Simplify if The statement ternary operator can effectively simplify if statements that only involve assignment and value operations, such as
var score = 60, grade;
if (score < 60) {
grade = "failed";
} else {
grade = “pass”;
}
can be simplified to:
var score = 60;
var grade = score < 60 ? “fail” : "Pass";
The ternary operator also supports nesting, but too many levels of nesting will affect the readability of the program, so more consideration should be given to this aspect.
1.3 Use JSON JSON is a lightweight data format. The lightweight is first reflected in its very simple structure definition.
var obj = {};
obj.p1 = 'a';
obj.p2 = 'b';
obj.p3 = 'c';
can be simplified to:
var obj = {
p1 : 'a',
p2 : 'b',
p3 : 'c'
};
2. Use efficient code
There are many efficiency optimization articles circulating on the Internet, and some more professional Javascript books also talk about them a lot, so here are only some that are rarely mentioned.
2.1 Simplify the loop body The efficiency of the loop is largely determined by the loop body. In comparison, the difference between using for or while is too small. Consider the following code, whose function is to add events to a certain batch of elements:
Copy code The 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 time the loop is executed, it will be judged whether the attachEvent or addEventListener of the window object exists. In fact, it is enough to judge only once; in addition, ""on" eventName" String concatenation will also be performed repeatedly. The optimization is as follows:
Copy code The 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 custom functions when you perform an operation on Javascript's built-in type variables , you should first check if there is a native method for this operation.
To make a copy of an array, what would you do? Iterating over the array elements and assigning them to another array one by one seems to be the only way. In fact, the native Array.prototype.slice can achieve the purpose of copying. This method returns selected elements from an array without affecting the original array. If the parameter is left empty, all elements are returned.
Array.prototype.slice can also operate on certain types that are not arrays but can be accessed through numeric indexes, such as
Copy code The code is 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 it doesn't work under IE.
Another example is array sorting. Under normal circumstances, we do not need to write another sorting algorithm, and the native Array.prototype.sort is enough. The sort method has only one parameter, which is a function that determines which of the two compared elements is in front and which is in the back. The default is to sort in character order, for example, 11 will be ranked before 2. To sort by numerical size, you can write:
Copy code The 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 attribute of the object:
Copy code The code is as follows:

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

2.3 Array deduplication The Array type does not provide deduplication Method, if you want to remove duplicate elements from the array, you have to think of a way yourself:
Copy code The 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 transfer the array elements to another array one by one. During the transfer process, check whether the element is duplicated, and if so, discard it directly. As can be seen from nested loops, this method is extremely inefficient. We can use a hashtable structure to record existing elements, so that the inner loop can be avoided. It just so happens that implementing hashtable in Javascript is extremely simple. The improvement is as follows:
Copy the code The 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 more readable and easier to maintain
Whether it is during or after development, keeping the code clear and easy to read can help you modify the code faster and more accurately .
3.1 Connecting HTML strings I believe that friends who are doing front-end development have suffered from this: when connecting HTML, they are dizzy due to the hateful single quotes and double quotes. For example:
element.innerHTML = '' text '';
Here is a string formatting function:
Copy code The 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 calling method is very simple:
Copy code The code is as follows:

element.innerHTML = String.format('%3', url, msg, text);

means replacing %n with the nth parameter. It will be much clearer this way.
3.2 Create a Config configuration object for your program. When writing a Java or C# program, we usually read the program's configuration information from XML. In Javascript, it is not cost-effective to use XML for configuration information. On the one hand, you need to request an additional XML file or convert an XML string into an XML object. On the other hand, the methods of XML objects are more complicated and lengthy. Lightweight JSON is the best choice.
The constants in the program should be placed in the Config configuration object, such as the URL of the Ajax request, the prompt of a certain operation, etc., for example:
Copy code The code is as follows:

var Config = {
ajaxUrl : "test.jsp",
successTips : "Request completed"
};

If there are a large number of Config, you can nest one more layer according to the configuration type, for example:
Copy code The 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 front of the program for easy viewing and modification.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template