for loopLOGIN

for loop

for(变量 = 初始值 ; 循环条件 ; 变量累加方法)
{
循环语句;
}

gives an example to illustrate more clearly. For example, printing out numbers from 0 to 7 in a loop:

<html>
<head>
</head>
<body>
<script>
for(var i=0;i<8;i++)
{
document.write("number is "+i+"<br>");
}
</script>
</body>
</html>

The effect in the browser:

QQ截图20161012132414.png

for loop The most commonly used place is to use indexes to traverse the array:

var arr = ['Apple', 'Google', 'Microsoft'];
var i, x;
for (i=0; i<arr.length; i++) {
    x = arr[i];
    alert(x);
}

The three conditions of the for loop can be omitted. If there is no judgment condition to exit the loop, you must use the break statement to exit the loop, otherwise it will be an infinite loop. :

var x = 0;
for (;;) { // 将无限循环下去
    if (x > 100) {
        break; // 通过if判断来退出循环
    }
    x ++;
}
<!DOCTYPE html>
<html>
<body>
<script>
cars=["BMW","Volvo","Saab","Ford"];
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
</script>
</body>
</html>

for ... in

A variation of the for loop is the for ... in loop, which can put an object All properties are cycled out in turn:

var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    alert(key); // 'name', 'age', 'city'
}

To filter out the properties inherited by the object, use hasOwnProperty() to achieve:

var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    if (o.hasOwnProperty(key)) {
        alert(key); // 'name', 'age', 'city'
    }
}

Since Array is also an object, and the index of each element of it is Considered as an attribute of the object, therefore, the for...in loop can directly loop out the Array index:

var a = ['A', 'B', 'C'];
for (var i in a) {
    alert(i); // '0', '1', '2'
    alert(a[i]); // 'A', 'B', 'C'
}


Next Section
<html> <head> </head> <body> <script> for(var i=0;i<8;i++) { document.write("number is "+i+"<br>"); } </script> </body> </html>
submitReset Code
ChapterCourseware