• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

3. Arrays and Objects > 3.10. Doing Something with a Property of an Object

Doing Something with a Property of an Object

NN 2, IE 3

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.

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.


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint