Home  >  Article  >  Web Front-end  >  JavaScript for loop from entry to side (efficiency optimization, strange usage)_javascript skills

JavaScript for loop from entry to side (efficiency optimization, strange usage)_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:51:291068browse
1. The basic writing method of for loop
The code is as follows:
Copy the code The code is as follows:

//Example 1 for(var i=1;i<=10;i) {
alert(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, i<10 in the first example is the condition. Only when the condition is true, the for loop will continue. The condition of the first example can be regarded as if(i<10){ //do...}. You can imagine that the basket can hold up to 10 things. If there are 10 more things, it will not be loaded and the loop will exit.
What 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:
Copy code The code is as follows:

//Example 2
var i=0;
for(;i<10;i ) {
alert(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:
Copy code The code is as follows:

//Example 3
var i= 0;
for(;i<10;) {
alert(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(;i<10;alert (i )) ;How? This is a scam, {} is gone! But it’s absolutely correct!
But 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:
Copy code The code is as follows:

var t = true;
if(t == true) {
alert('Ah!')
}

No one can understand this if statement. In fact, it can be written like this:
Copy code The code is as follows:

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

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

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:
Copy the code The code is as follows:

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

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:
Copy the code The code is as follows:

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

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:
Copy the code The code is as follows:

var arr = [1,2,23,1000];
for(var i=0,l = arr.length;iif(arr[i]>10000) {
i ;
}
}
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