


JavaScript for loop from entry to side (efficiency optimization, strange usage)_javascript skills
The code is as follows:
//Example 1 for(var i=1;ialert(i);
}
This code It's so simple that I'm embarrassed to take it out. The execution result of the code is that 1 to 10 pop up in sequence. PS: In early IE such as IE6, if you change 10 to 10000, the user will keep clicking to confirm that nothing can be done. Haha - don't say it was my idea. .
Since this is a basic course, let’s get back to the topic and analyze this code in detail.
The structures of for loops are similar. Any for loop is like this:
for (before starting; conditions for loop execution; what to do after the loop ends) {
// Main body code
} If you take a closer look at the for loop, you will find one of its characteristics that remains unchanged for thousands of years: there are always two and only two; (English semicolons) in () after for!
The above structure The code has explained that the semicolon is used to separate the execution conditions of the for loop. These conditions are indispensable and can be empty, but the position must be reserved, so there must be two;.
Before starting: It is generally used to declare some variables, such as var i=0 in Example 1, which is like preparing a basket with nothing in it for the time being. There is no limit to the number of tools, you can declare 100 variables before the for loop starts, and there's nothing wrong with it except that it doesn't look good.
Conditions for the loop to proceed: For example, iWhat to do after looping once: In Example 1, you just simply add something to the basket. In fact, you can do many things. After all, looping once is not easy.
Special note: The code "before the start" of the for loop will only be executed once and will not affect the efficiency of the entire for loop. However, the "progress condition" and "what to do after the end" will be determined by how many times you loop. Executed many times, so they often become for loop performance bottlenecks.
If the first; in the for loop is what was done before the start, then can I bring the things before the start to the front of the for loop? Just define it before you start. The answer is yes:
//Example 2
var i=0;
for(;ialert(i);
}
But please note that although the "start" in the brackets after for "before" has no content, but the ; (semicolon) is still there! And it must be there!
Similarly, since the code after the second; is executed after one time, I can also put the code to be executed after the for loop. As follows:
//Example 3
var i= 0;
for(;ialert(i);
i
}
But still, the two evil; must still exist .
The above are the two basic "side usages". . . Don’t say I’m cheating
But as you can see, the conditions for executing the loop cannot be stated separately, they must be placed between two semicolons! Attack from both front and back!
2. The partial way of writing the for loop
1. We change the code of Example 1 into:
var i=0;
for(;iBut this way of writing is too outrageous, number 2; it is best not to have too much code in the back, because once it is too much, you will not be able to grasp the value of i, and because the code is confusing, it may lead to artificial grammatical errors.
Applicable environment:
For simple for loop operations, such as creating an array whose elements are numbers from 1 to 1000, use this trick, it is cool in one word.
2. In-depth analysis
From the previous example, we know that in fact, the execution condition of the for loop is to judge a Boolean value, like this:
var t = true;
if(t == true) {
alert('Ah!')
}
No one can understand this if statement. In fact, it can be written like this:
var t = true;
if(t) {
alert('Ah!')
}
The effect is the same. If the condition of the for loop is to judge a Boolean value, then the following writing method is not difficult to understand:
var i = 10;
for(;i;i--){
alert(i);
}
The effect of this code is to pop up 10 to 1 in sequence (reversed from Example 1). The condition for the for loop is as simple as i. But according to our previous explanation, the condition is actually like this:
if(i) {
//do
}
That is, if i is true, continue execution cycle. When is i in this for loop true? As long as i is not equal to 0, empty string, undefined, null, or false, it is true.
So this for loop will be executed until i=0, then it ends. But we will not see 0 in our code, which will confuse novices and install B as a weapon.
3, another
first look at the code, from garden friend snandy:
var ary = ["jack","tom","lily","andy"];
for(var i=0,a;a=ary[i ];){
console.log(a);
}
Still pay attention to the condition of the for loop: a=ary[i]. Pay special attention to = instead of ==. If it is ==, the loop will not proceed.
This conditional judgment is ridiculous, and I am also confused. Similar to:
if(a=b) {...} //Note it is =!
If b is false at this time, it will return false.
Going back to the above example, if i adds a header, then ary[i] has a false value (both null and undefined count), so the condition becomes false, so the loop is broken.
This example has great limitations, as snandy also mentioned. For example, if there is a 0 in your array, it may also cause the loop to terminate.
4, a way of writing jQuery
function sibling( elem ) {
var r = [],
n = elem.parentNode.firstChild;
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
This is from jquery The way to extract the sibling nodes is a unique for loop. The condition for looping is to determine whether n is true. Since n is always an html node, it is always true. After each loop ends, the next node of n will be assigned to n. When there is no next node of n, n will become false and the loop will be terminated.
Summary:
As you can see from all the above examples, no matter how strange the for loop is, it cannot do without two;. If you want to understand the principle of a for loop, you can just divide the for loop with ; as the boundary, and it will be clear at a glance.
3. Efficiency optimization of for loop
1. Cache variables
This is also the most commonly used efficiency optimization method:
var arr =[1,2,23,...,1000];
for(var i=0, l = arr.length;i
}
Since the execution condition must be judged every time it loops, if it is determined from arr every time it loops Reading length is undoubtedly very wasteful and will inevitably increase the number of calculations, resulting in a waste of efficiency.
2, reverse order method
For example, if an array has 1000 elements, if the extraction order is not considered, you can loop in reverse order:
var arr =[1,2,23,...,1000];
var i = arr.length;
for(; i>0;i--){
//alert(i);
}
Why is reverse order faster than sequential order? There is no scientific reason! In fact, it's just because one less variable can be used in reverse order (compare this to the previous example). Apart from this, there is no speed difference between the two.
3. Pay attention to jumping out
and do not perform unnecessary operations. This is the basic logic. If there are 1,000 li's, one li has a special className, and we need to find this li. Then, since it has been determined that there is only one such li, we should jump out immediately when we find this li, break, and there is no need to proceed with the following loop. In this way, since li has a 999/1000 chance of not being the last one, we can definitely save a lot of calculations.
For other situations, please draw inferences.
4. Use sideways usage
The sideways usages I introduced above are not only beautiful to write, most of them have the effect of saving variables and calculations. Just use it if you can, it is cool and effective, why not? Why not?
----------------------------------Summary------------------ ----------------
I like the flexibility of Javascript, not just because it can be used to look cool. I hope to learn more JS knowledge in the blog park. I often read the articles of experts and benefit a lot. Below are some of the great people I found in the garden. It’s incomplete. If I don’t list them, don’t curse me.
cloudgamer, Situ Zhengmei, Uncle Tom, snandy and other low-key masters. If you want to find their blog, just search it.
PS: I really like the code insertion function of the Blog Park. In the future, articles involving a large amount of code will be posted directly to the Blog Park.
Don’t try the following code:
var arr = [1,2,23,1000];
for(var i=0,l = arr.length;i
i ;
}
}

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 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 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.

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.

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.

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.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft