1. Computing & Technology

JavaScript By Example

23. For..In

From , former About.com Guide

One loop variant we did not cover earlier is the for..in loop. The reason for this is that for..in loops are not for general use but instead are specifically for use in processing objects. A for..in loop iterates over all of the enumerable properties and methods of an object allowing you to perform processing on all of those methods and properties regardless of what they are named or how many there are.

Note that the built in objects have some of their properties and methods defined as non-enumerable which specifically means that those methods and properties will not be included in those to be processed by a for..in loop. With objects that you define of your own you can inherit the non-enumerable properties and methods from the built in object you are copying but you cannot create your own non-enumerable properties or methods.

In this example we retrieve all of the properties and methods of a date object that contains today's date.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 23</title>
</head>
<body>
<p id="ex"></p>
<script type="text/javascript" src="example23.js"></script>
</body>
</html>

JavaScript


var today, out;
today = new Date();
out = Values : ';
for (x in today) {
  out += x + ',';
}
document.getElementById('ex').innerHTML = out;

©2012 About.com. All rights reserved.

A part of The New York Times Company.