Enumerating Properties
Instead of testing for the existence of individual properties,
we sometimes want to iterate through or obtain a list of all the
properties of an object. This is usually done with the for/in loop, although ECMAScript 5 provides
two handy alternatives.
The for/in loop was covered
in for/in. It runs the body of the loop once for
each enumerable property (own or inherited) of the specified object,
assigning the name of the property to the loop variable. Built-in
methods that objects inherit are not enumerable, but the properties that your
code adds to objects are enumerable (unless you use one of the
functions described later to make them nonenumerable). For example:
varo={x:1,y:2,z:3};// Three enumerable own propertieso.propertyIsEnumerable("toString")// => false: not enumerablefor(varpino)// Loop through the propertiesconsole.log(p);// Prints x, y, and z, but not toString
Some utility libraries add new methods (or other properties) to
Object.prototype so that they are
inherited by, and available to, all objects. Prior to ECMAScript 5,
however, there is no way to make these added methods nonenumerable, so
they are enumerated by for/in
loops. To guard against this, you might want to filter the properties
returned by for/in. Here are two
ways you might do so:
for(pino){if(!o.hasOwnProperty(p))continue;// Skip inherited properties}for(varpino){if(typeofo[p]==="function")continue;// Skip methods}
Example 6-2 defines utility functions ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access