search
HomeWeb Front-endJS TutorialJavascript code can also become beautiful implementation method_javascript skills

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 grade = "failed";
} else {
grade = “pass”;
}
can be simplified to:
var score = 60;
var grade = score 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 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 elems[i].attachEvent(eventName, handler);
}
} else if (window.addEventListener) {
while ( i 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 isRepeated = false;
for (var j = 0, len = result.length; 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.
Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor