JavaScript for in loop

for ... in loop to iterate attribute object.

Its syntax is as follows

for (variable in object) {

     // loop

}

. 1  <! DOCTYPE HTML > 
2  < HTML > 
. 3  < head > 
. 4  < Meta charset = "UTF-. 8" > 
. 5  < title > for in loop ... </ title > 
. 6  </ head > 
. 7  < body > 
. 8  < Script > 
. 9  
10  var value;
 . 11   / * *
 12 is     * here is traversing document object attributes, and then assigned to * value
 13 is     * println (value); print function call println * /
14  for (value in Document) {
 15      the println (value);
 16  }
 . 17   
18 is  function the println (A) {
 . 19      document.write (A);
 20 is      document.write ( ' <br> ' );
 21 is  }
 22 is  
23 is  Document. Write ( ' <br> ' );
 24  
25  var pig = {}; // literal create objects pig object variable name, object name may be called 
26 is      
27      // set literal object property 
28      pig.name =  'Pig ' ;
 29      pig.age = . 3 ;
 30      pig.appetite = . 3 ;
 31 is      pig.eat = function () {
 32          document.write ( ' are eating ' );
 33 is      }
 34 is      
35      for (X in Pig) {
 36          Document .write (X + " <br> " );
 37 [      }
 38 is      
39      / * *
 40        * this is the value in the array assigned to each value x, then traversing out * / 
41     var array =[2,4,1,5,3,6,8,9,7,0];
42     
43     for(x in array){
44         document.write(array[x]+"<br>");
45     }
46 </script>
47 </body>
48 </html>

for in addition to traverse the loop at the JavaScript built-in objects, but also can traverse the custom object.

operation result:

Guess you like

Origin www.cnblogs.com/hzyhx/p/11139762.html