JavaScript for ...LOGIN

JavaScript for loop

JavaScript for loop

Loop can execute a code block a specified number of times.

JavaScript Loops

Using a loop is convenient if you want to run the same code over and over again, with different values ​​each time.

We can output the value of the array like this:

General writing method:

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

Different types of loops

JavaScript supports different types of loops:

for - loop code block a certain number of times

for/in - loop Traverse the properties of the object

while - Loop the specified code block when the specified condition is true

do/while - Loop the specified code block also when the specified condition is true

For Loop

The for loop is a tool that you will often use when you want to create a loop.

The following is the syntax of the for loop:

for (statement 1; statement 2; statement 3)
{
Executed code block
}

Statement 1 (code block) is executed before starts.

Statement 2 defines the conditions for running the loop (code block)

Statement 3 is executed after the loop (code block) Then execute

点击按钮循环代码5次。点击这里function myFunction(){
    var x="";
    for (var i=0;i";
    }
    document.getElementById("demo").innerHTML=x;
}
Next Section
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>点击下面的按钮,循环遍历对象 "person" 的属性。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction(){ var x; var txt=""; var person={fname:"Bill",lname:"Gates",age:56}; for (x in person){ txt=txt + person[x]; } document.getElementById("demo").innerHTML=txt; } </script> </body> </html>
submitReset Code
ChapterCourseware