HTML and CSS Reference
In-Depth Information
For an array object, the only enumerable properties are its numeric indexes.
The methods and the length property provided by Array.prototype are not
enumerable. This is why a for-in loop will only reveal the indexes and their
associated values for array objects. However, when we add properties to an object
or one of the objects in its prototype chain, they are enumerable by default. Because
of this fact, these new properties will also appear in a for-in loop, as shown by
the test failure above.
I recommend you don't use for-in on arrays. The problem illustrated above
can be worked around, as we will see shortly, but not without trading off per-
formance. Using for-in on arrays effectively means we can't normalize browser
behavior by adding missing methods to Array.prototype without inferring a
performance hit. Object.prototype.hasOwnProperty
Object.prototype.hasOwnProperty(name) returns true if an object
has a property with the given name. If the object either inherits the property from
the prototype chain, or doesn't have such a property at all, hasOwnProperty
returns false . This means that we can qualify a for-in loop with a call to
hasOwnProperty to ensure we only loop the object's own properties, as seen in
Listing 7.9.
Listing 7.9 Qualifying a loop with hasOwnProperty
"test looping should only iterate over own properties":
function () {
var person = {
name: "Christian",
profession: "Programmer",
location: "Norway"
var result = [];
for (var prop in person) {
if (person.hasOwnProperty(prop)) {
var expected = ["location", "name", "profession"];
assertEquals(expected, result.sort());
Search WWH ::

Custom Search