for loop
for(變量 = 初始值 ; 循環(huán)條件 ; 變量累加方法) { 循環(huán)語句; }
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:
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 (;;) { // 將無限循環(huán)下去 if (x > 100) { break; // 通過if判斷來退出循環(huán) } 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' }