JavaScript for loop _javascript tips from getting started to the partial gate (efficiency optimization + fancy usage)

Source: Internet
Author: User
The basic writing of a For loop
The code is as follows:
Copy Code code as follows:

Example one for (Var i=1;i<=10;i++) {
alert (i);
}

This piece of code is too simple, I am embarrassed to take the shot. The result of the code is to pop 1 to 10,ps in turn: In earlier IE like IE6, you changed 10 to 10000, allowing users to always point out that nothing could be done. Haha-don't say it was my idea.
Since this is a basic course, let's go back to the topic and analyze the code in detail.
The structure of the For loop is similar, as is the case for any for loop:
for (before; the condition of the loop; What to do after one end of the loop) {
Body Code
If you take a closer look at the For loop, you will find that one of his permanent features: for the post (), there will always be and only two, (English semicolon)!
The structure code above shows that the semicolon is used to split the execution condition of the For loop. These conditions are indispensable, can be empty, but the position must be kept, so there must be two;.
Before beginning: Generally used to declare some variables, such as example of the Var i=0, just like a basket, there is nothing in it for the time being. There are no limits to the number of tools, you can declare 100 variables before the for loop starts, and there's nothing wrong with it except for the look.
Cyclic conditions: As in the 1th example of the i<10, is the condition, only if the condition is true, the For loop will go on, for example one of the conditions can be seen as if (i<10) {//do ...}. Can imagine a basket of up to 10 things, if more than 10, will not install, exit the loop.
What to do after a loop: example one is simply to add a thing to the basket, in fact you can do a lot of things, after all, the cycle is not easy.
Special note: For loop "before" the code will only be executed once, does not affect the overall for loop efficiency, and "What to Do" and "after the end", how many times you cycle, he executes how many times, so they often become a for loop performance bottleneck.
If the For loop is the 1th, before it's the first thing to do, can I get the first thing before the for loop? Just define it before you start. The answer is yes:
Copy Code code as follows:

Example 2
var i=0;
for (; i<10;i++) {
alert (i);
}

Note, though, that there is no content before "start" in parentheses for the back, but (semicolon) still! and must be in!
Similarly, since the 2nd, followed by the end of the code after the execution, then I can also put to do after the for loop AH. As follows:
Copy Code code as follows:

Example 3
var i=0;
for (;i<10;) {
alert (i);
i++
}

But still, two of all evils must exist.
Above is the two basic "partial gate usage" ... Don't say I pit dad
But as you can see, the conditions for performing loops cannot be raised separately, and must be placed between two semicolons! Back and forth!
Two, the partial gate writing for The loop
1, we turn the code of example one into:
var i=0;
for (; I<10;alert (i++)); How about it? This is the pit dad, {} none! But absolutely right!
But this kind of writing is too adverse days, the 2nd, the code behind the best not much, a more than you can not grasp the value of I, and because the code confusion can lead to man-made grammatical errors.
Applicable environment:
Simple for-loop operations, such as making an element of an array of numbers from 1 to 1000 in turn, use this trick, cool on one word.
2, in-depth analysis
As we know in the previous example, the execution condition for a for loop is to judge a Boolean value, like this:
Copy Code code as follows:

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

No one can read this if statement, in fact, it is also possible to write:
Copy Code code as follows:

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

The effect is the same, if the For loop's condition is to judge the Boolean value, then the following wording is not difficult to understand:
Copy Code code as follows:

var i = 10;
for (; i;i--) {
alert (i);
}

The effect of this code is to pop 10 to 1 in turn (and the example one in turn). The condition of the For loop is simply dying, which is an I. But according to our previous explanation, the condition is this:
Copy Code code as follows:

if (i) {
Todo
}

That is the case where I is true, I continue to execute the loop. This for loop I when is true, as long as I do not equal 0, empty string, Undefined,null,false, all true.
So this for loop will always execute until i=0, and it's over. But we will not see 0 in the code, confuse novice, install B sharp weapon.
3, another one.
First look at the code, from the Garden friends Snandy:
Copy Code code 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 here is = instead of = =, if = = Word cycle can not be carried out.
This condition judgment is very ridiculous, I also compare dizzy. Similar to:
if (a=b) {...}//Note Yes =!
At this point, if B is false, it returns false.
In the example above, if the i++ adds a header, the ary[i++] is False (null,undefined), so the condition becomes false, so the loop breaks.
This example is very limited, Snandy also mentioned, for example, you have an array of 0, which may also cause the end of the loop.
A writing of 4,jquery
Copy Code code 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 the way to get the sibling node from jquery, and he has a peculiar for loop. The condition of the loop is to determine whether N is true. Since n is always an HTML node, it is always true. At the end of each loop, the next node of n is assigned to N, and when the next node of n is not, N becomes false, ending the loop.
Summary:
From all the above examples can be seen, any of his strange for the loop, are inseparable from two; You want to understand the principle of a for loop, directly to the boundary for the partition for loop can be, at a glance.
third, the efficiency optimization for The loop
1, Cache variables
This is also the most common method of efficiency optimization:
Copy Code code as follows:

var arr =[1,2,23,..., 1000];
for (var i=0,l = arr.length;i<l;i++) {
//
}

Because the implementation of the conditions of each cycle to be judged, so if each cycle from the arr read length, it is undoubtedly wasteful and inevitably increase the number of calculations, resulting in inefficient waste.
2, Reverse method
For example, an array has 1000 elements, and if you do not consider the extraction order, then you can loop backwards:
Copy Code code as follows:

var arr =[1,2,23,..., 1000];
var i = arr.length;
for (; i>0;i--) {
alert (i);
}

Why is the reverse faster than the sequential efficiency? There is no scientific reason! In fact, just because the reverse can be less than a variable (compared to the previous example), except for this, there is no speed difference between the two.
3, pay attention to jump
This is the basic logic of not doing unnecessary operations. If there are 1000 li inside, there is a special classname on Li, we have to find this li. So, since we have identified only one such Li, we should jump right out of the way, break, and the following loops are unnecessary. So, since Li has a 999/1000 chance of not being the last, we can certainly save a lot of calculations.
Please extrapolate other information.
4, use the partial gate usage
The above I introduced the partial door usage not only is writes to look good, most have the saving variable to save the computation the effect, can use, is cool and effective, why not?
----------------------------Summary--------------------------------
I like the flexibility of JavaScript, not just because it can be used to cool. Hope that in the blog park to learn more JS knowledge, Daniel's article I often see, a lot of benefits. Here are some of the cows I found in the garden, not all of them, no lists. Don't curse me.
Cloudgamer, Masaki, Uncle Tom, Snandy and other too low-key masters. Want to find their blog directly search it.
PS: Really like the insertion of the blog Park code function, later involved in a large number of code articles are directly sent blog Park Bar.
Do not try the following code:
Copy Code code as follows:

var arr =[1,2,23,1000];
for (var i=0,l = arr.length;i<l;) {
if (arr[i]>10000) {
i++;
}
}
Related Article

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.