Javascript Data Type How to - Loop through object like an array








Question

We would like to know how to loop through object like an array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.4.2.js'></script>
<script type='text/javascript'>
var myArray = { title: "my title", 
                description: "my description" 
              };<!-- w  w  w  . j  a  va2 s. com-->
var i = 0;
for(var i in myArray) {
   document.writeln('The '+ i + ' is ' + myArray[i]);
}

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: