3.10 Doing Something with a Property of an Object
NN 2, IE 3
3.10.1 Problem
You
want to examine (or modify) the values of properties belonging to an
object, but the object and its properties may change from one
examination to another.
3.10.2 Solution
Use a for/in loop to access
every property of an object, regardless of the
property's name. The following function assembles a
list of properties and their values for any object passed as an
argument to the function:
function listProperties(obj, objName) {
var result = "";
for (var i in obj) {
result += objName + "." + i + "=" + obj[i] + "\n";
}
alert(result);
}
In this special type of loop, the variable (i in
this example) is automatically assigned the name of each property (in
string form) as the loop progresses through the list of available
properties for the object. By using the string name as an index to
the object (obj[i] in this example), the value of
that property is returned.
3.10.3 Discussion
Figure 3-1 show what the alert dialog box generated
by the function would display for one of the sales
objects defined in Recipe 3.9.
The type of property enumeration shown in the
listProperties(
) function in the Solution is useful not
only for custom objects but also for DOM objects. When using it with
DOM objects, some browser-specific behaviors reveal themselves. For
example, IE for Windows enumerates all of the event handler
properties of the object. Netscape 6 and later enumerate properties
and methods. Unfortunately, Opera does not handle DOM objects, but
the for/in type of looping
works with custom objects.
3.10.4 See Also
Recipe 3.4 for looping through all entries of an array.
|