This loop is used with arrays and objects , to access their elements and properties respectively.
In for..in looping the variable starts from zero and increases itself with one until it reach to the length of array. |
Syntax: |
for( variablename in objectname)
{ lines to be executed } |
Example: |
<html>
<head> </head> <body> <script type=”text/javascript”> var color; var shop=new Array() shop[0]=”Red” shop[1]=”Blue” shop[2]=”Green” shop[3]=”Yellow” shop[4]=”Magenta” for(color in shop) { document.write(“<br> “+shop[color]); } </script > </body> </html> |
Understanding program: |
Color is a undefined variable and shop is an array, when color is kept as a subscript of array shop then the color variable becomes of number type and from 0 to 4 gets incremented by for – in loop. It is increased up to 4 only because shop array have 5 elements and an array start from 0 position. |
Output is: |
Red Blue Green Yellow Magenta |