Javascript for Loop statement learning notes

Source: Internet
Author: User

A for loop has an initial value and an end value to form a closed loop. If you want to die for a loop, as long as the step size remains unchanged, I will introduce the angle between the for loop.

For Loop

A for Loop is a tool that you often use to create a loop.

The syntax of the for Loop is as follows:

For (Statement 1; Statement 2; Statement 3)
{
Executed code block
}

Statement 1 is executed before the cycle (code block) begins.

Statement 2 defines conditions for running loops (code blocks)

Statement 3 is executed after the loop (code block) has been executed

The basic structure is as follows:

The Code is as follows: Copy code
For (initial condition; test condition; alter condition ){
Statements;
}

The meanings of parameters in the cyclic control code (that is, the code in parentheses) are as follows:
• Initial condition: indicates the initial value of the cyclic variable;
• Test condition: A condition expression that controls whether a loop ends or not. Each time the program executes a loop body statement (or statement block), it calculates whether the expression is true. If the result is true, the next loop continues. If the result is false, the loop body jumps out.
• Alter condition: This method is used to update cyclic variables. Every time a program executes a loop, it must update the cyclic variables.

The preceding parameters are separated by semicolons.

[Example 3-4] calculate the value of 1 + 2 + 3... + 98 + 99 + 100:

The Code is as follows: Copy code
<Html>
<Head>
<Title> calculate the value of 1 + 2 + 3... + 98 + 99 + 100 </title>
</Head>
<Body>
<Script language = "JavaScript" type = "text/javascript">
Var total = 0;
For (var I = 1; I <= 100; I ++ ){
Total + = I;
}
Alert (total );
</Script>
</Body>
</Html>

Next let's look at it.

In a for loop, you can obtain the values of arrays or arrays similar to objects, such as arguments and HTMLCollection objects. The general cycle is as follows:

The Code is as follows: Copy code

// The second best cycle
For (var I = 0; I <myarray. length; I ++ ){
// Use myarray [I] to do something
}

The disadvantage of this type of loop is that the length of the array needs to be obtained at each loop. This reduces your code, especially when myarray is not an array but an HTMLCollection object.

HTMLCollections refers to the object returned by the DOM method, for example:

Document. getElementsByName ()
Document. getElementsByClassName ()
Document. getElementsByTagName ()


There are other HTMLCollections, which were introduced before the DOM standard and are still in use. Include:

Document. images: All image elements on the page
Document. links: All a tag Elements
Document. forms: All forms
Document. forms [0]. elements: all fields in the first form on the page


The trouble with collections is that they query Basic Documents (HTML pages) in real time ). This means that every time you access the length of any set, you need to query the DOM in real time, and DOM operations are generally expensive.

This is why when you get the value cyclically, the length of the cached array (or set) is better, as shown in the following code:

The Code is as follows: Copy code

For (var I = 0, max = myarray. length; I <max; I ++ ){
// Use myarray [I] to do something
}

In this way, you only retrieve the length value once in this loop.

In all browsers, the length of the cache HTMLCollections is faster when the content is obtained cyclically, between 2 times (Safari3) and 190 times (IE7. // This data looks very old for reference only

Note that when you explicitly want to modify the set in the loop (for example, adding more DOM elements), you may prefer length update instead of constants.

With the single var form, you can extract variables from the loop, as shown below:

The Code is as follows: Copy code

Function logoff (){
Var I = 0,
Max,
Myarray = [];
//...
For (I = 0, max = myarray. length; I <max; I ++ ){
// Use myarray [I] to do something
}
}

This form has the benefit of consistency because you stick to the single var form. The disadvantage is that it is difficult to copy and paste the entire loop when refactoring the code. For example, if you copy a loop from a function to another function, You have to determine that you can introduce I and max to a new function (if it is useless here, it is very likely that you will delete them from the original function ).

To adjust the loop, replace I ++ with one of the following expressions.

The Code is as follows: Copy code

I = I + 1
I + = 1

JSLint prompts you to do this because ++ and -- promote "excessive trickiness )". If you ignore it directly, the plusplus option of JSLint will be false (default ).

There are two other forms of change, which are slightly improved because:

• One Variable missing (without max)
• Counting down to 0 is usually faster, because comparing with 0 is more efficient than comparing with array length or other things that are not 0
// The first form of change:

The Code is as follows: Copy code

Var I, myarray = [];
For (I = myarray. length; I --;){
// Use myarray [I] to do something
}

// The second method uses the while loop:

Var myarray = [],
I = myarray. length;
While (I --){
// Use myarray [I] to do something
}

These minor improvements are only reflected in performance, and JSLint will complain about using 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.