JavaScript Basic Teaching for Loop _ basics

Source: Internet
Author: User

If you want to run the same code over and over again and the values are different each time, it's convenient to use loops.

Copy Code code as follows:

document.write (Cars[0] + "<br>");
document.write (Cars[1] + "<br>");
document.write (cars[2] + "<br>");
document.write (Cars[3] + "<br>");
document.write (Cars[4] + "<br>");
document.write (Cars[5] + "<br>");

But that's what we write.

Copy Code code as follows:

for (var i=0; i<cars.length;i++)
{
document.write (cars[i]+ "<br>");
}

Example: Output 1-100 of the number

Copy Code code as follows:

for (var i=0;i <=100;i++)
{
document.write (i+ "<br>")
}

For is the pre-test loop, and can initialize the variable before the loop, and define the code to execute after the loop, with the following syntax

for (inintialization;expression;psot=loop-expression) statement

The process of execution is as follows:

1. Execute initialization statement

2. To determine whether expression is true, if it is to continue, otherwise terminate the entire circulation body.

3. Execute Loop Body Statement code

4. Execute post-loop-expression Code

5. Return to step 2nd operation

The most common form for a For loop is for (var i=0; i<n;i++) {statement}

It means that the loop performs a total of n times, which is ideal for known loop count operations.

Copy Code code as follows:

var anumbers = new Array ();
var smessage = "you entered: \ n";
var itotal = 0;
var vuserinput;
var iarrayindex = 0;
do{
Vuserinput = Prompt ("Enter a number, or ' 0 ' exit", "0");
Anumbers[iarrayindex] = vuserinput;
iarrayindex++;
Itotal + = number (vuserinput);
Smessage + = vuserinput + "\ n";
}while (vuserinput!= 0)//exit loop body when entered as 0 (default)
Smessage + = "Total:" + itotal;
document.getElementById ("xxx"). Innerhtml=smessage;

The above is all about the For loop in JavaScript, and I hope the little friends like it.

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.