Javascript: For loop from entry to partial door, efficiency optimization, strange usage

Source: Internet
Author: User

For Loop is a very basic JavaScript knowledge, but because Javascript is too flexible, there may be some writing that causes beginners to crash. I decided to explain the For Loop in a simple way. It would be helpful for new users who are still new to me to avoid detours.

I. Basic for loop writing

CodeAs follows:

 
// Example 1
For(VaRI = 0; I <10; I ++) {Alert (I );}

This code is too simple and I am so embarrassed to come up with it. The code execution result is displayed in sequence.1 to 10, (Correction: 0-9 ). PS: in earlier versions of Internet Explorer such as Internet Explorer 6, you changed 10 to 10000, so that users can always be certain and cannot do anything. Haha-Don't say it's my idea.

As this is a basic course, let's go back to the subject and analyze the code in detail.

The structure of the For Loop is similar, and any for loop is like this:

 
For(Before the start; conditions for loop execution; what to do after the end of a loop ){//Subject Code}

If you take a closer look at the for loop, you will find that his 10 thousand years remain unchanged:In () after for, there will always be and only two; (semicolon )!

The preceding Structure Code shows that the semicolon is used to separate the execution conditions of the for loop. These conditions are all indispensable and can be blank, but the location must be kept, so there must be two ;.

Before: It is generally used to declare some variables, such as VAR I = 0 in Example 1. It is like preparing a token, which has nothing at the moment. The number of tools is not limited. You can declare 100 variables before the for loop starts, except for poor reading.

Cyclic Conditions: For example, I <10 in the 1st example is a condition. The for loop continues only when the condition is true. The condition in Example 1 can be considered as if (I <10) {// do ...}. As you can imagine, a batch can hold up to 10 items. If there are 10 more items, it will not be installed and the loop will exit.

What do I do after one loop?: In this example, you can simply add something to the notebook. In fact, you can do a lot of things. After all, it is not easy to loop once.

Note: The code before the for loop "starts" is executed only once, without affecting the efficiency of the entire for loop, while the "conditions" and "what to do after one end ", the number of cycles you have and the number of times it executes, so they often become the bottleneck of the For Loop performance.

If we say there are 1st for loops; the first is what we did before the start, can I get the previous thing before the for loop? Just define it before you start. The answer is yes:

//Example 2VaRI = 0;For(; I <10; I ++) {Alert (I );}

However, you should note that, although there is no content before the start in the brackets behind the for, the; (semicolon) is still there! And must be in!

Similarly, since there are 2nd; the Code that follows is executed after one end, I can also put the code to be executed after the for loop. As follows:

 
//Example 3VaRI = 0;For(; I <10;) {Alert (I); I++}

But it still exists.

The above are two basic "partial door usage... Don't talk about me.

But as you can see, the condition for executing the loop is:NoWhich can be proposed separately must be placed between two semicolons! Before and after attacks!

2. Partial writing of For Loop

1. Let's change the code of Example 1:

VaRI = 0;For(; I <10; alert (I ++ ));

How is it? This is the trap! {} is gone! But it is completely correct!

But this writing method is too much against the day, 2nd; it is better not to have more code behind, you cannot grasp the value of I, and because of code chaos, it may lead to human syntax errors.

Applicable environment:

Simple for loop operations, such as creating an array of numbers from 1 to 1000 in sequence, use this method, cool is just a word.

2. In-depth Analysis

The preceding example shows that the execution condition of the for loop is to judge a Boolean value, as shown in the following code:

 
VaRT =True;If(T =True) {Alert ('Ah! ')}

No one can understand this If statement. You can write it like this:

VaRT =True;If(T) {alert ('Ah! ')}

The effect is the same. If the condition for the for loop is to judge the Boolean value, it is not difficult to understand the following method:

 
VaRI = 10;For(; I --) {Alert (I );}

The effect of this Code is to pop up 10 to 1 (not 9 to 0) in sequence ). The for loop is simply executed, but according to our previous explanation, the conditions are as follows:

 
If(I ){//Do}

That is, if I is true, the execution will continue. When is the I of this for loop true, as long as I is not equal0, empty string, undefined, null, falseIs true.

Therefore, the for loop is executed until I = 0. However, we won't see 0 in the code, confusing new users and installing B.

3. Another

Let's look at the code first. snandy:

 
VaRAry = ["Jack", "Tom", "Lily", "Andy"];For(VaRI = 0, A; A = ary [I ++];) {Console. Log ();}

Still pay attention to the conditions for running the For Loop: A = ary [I ++]. Note:=Instead of =, if =, the loop won't be able to proceed.

This condition is very difficult to judge and I am also dizzy. Similar:

If (A = B) {...} // note =!

In fact, this code is equivalent:

 
A =B;If(){//Do}

That is, assign values first and then judge. If B is false, A is false, so the condition is false.

Return to the example above, if I ++ adds a header, then ary [I ++] is false (null, undefined), so the condition becomes false, so the loop is broken.

This exampleLimitationsAs mentioned in snandy, for example, if your array contains a value of 0, the loop may end.

4. A jquery Method

 
FunctionSibling (ELEM ){VaRR =[], N=ELEM. parentnode. firstchild;For(; N =N. nextsibling ){If(N. nodetype === 1 & n! =ELEM) {R. Push (n );}}ReturnR ;}

This is the way to obtain the sibling node extracted from jquery. He has a strange for loop. The condition for loop is to judge whether N is true. Since N is always an HTML node, it is always true. After each loop ends, the next node of N is assigned to n. When the next node of N is absent, n is set to false to terminate the loop.

Summary:

From all the examples above, we can see that any of his strange for loops is inseparable.Two;. Everyone wants to understand the principle of a for loop, and you can simply separate the for loop with a; line.

3. Efficiency Optimization of the For Loop

1. cache Variables

This is also the most common efficiency optimization method:

 
VaRArr = [1000, 23 ,...,];For(VaRI = 0, L = arr. length; I <L; I ++){//}

Since the execution condition must be determined for each loop, if the length is read from arr for each loop, it is a waste of time and will inevitably increase the number of computations, resulting in low efficiency.

2. Reverse Order Method

For example, an array has 1000 elements. If you do not consider the extraction order, you can perform an inverted loop:

VaRArr = [1000, 23 ,...,];VaRI =Arr. Length-1;For(; I> = 0; I --){//Alert (I );}

Why is reverse order more efficient than sequential order? No scientific reason! In fact, it is only because the reverse order can use less variable (compare with the previous example). Apart from this, there is no speed difference between the two.

3. Note that

This is the basic logic. If there are 1000 li and one Li has a special classname, we need to find this Li. So, as we have determined that there is only one such Li, we should jump out immediately when we find this Li, break, and the following cycle is unnecessary. In this way, because the probability of Li is 999/1000 is not the last one, we can certainly save a lot of computing.

In other cases, please refer to the opposite.

4. Use a portal

I have introduced more than just a good-looking method. Most of them have the effect of saving variables and saving computing. They can be used only when they are used. They are both cool and effective. Why not?

----------------------------Summary--------------------------------

I like the flexibility of JavaScript, not just for cool installation. I hope I can learn more about Js in my blog.ArticleI often see that there are many benefits. Below are some cool people I have found in the garden, not all. If they are not listed, don't curse me.

Cloudgamer, situ zhengmei, Uncle Tom, snandy, and other low-key experts. Search for their blog.

PS: I really like the function of inserting code in the blog garden. In the future, articles that involve a lot of code will be sent directly to the blog garden.

Do not try the following code:

 
VaRArr = [,];For(VaRI = 0, L = arr. length; I <L ;){If(ARR [I]> 10000) {I++;}}

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.