I'm trying to do a bit of browser object discovery, figuring out browser built-ins etc...
I noticed different results when trying to get at the window object's properties (just FYI I'm using Chrome Version 41.0.2272.89 (64-bit)).
Object.keys(window).length;
returns 7 keys. From the docs Object.keys() returns the enumerable properties of an object.
But the docs also say that for ... in
iterates over the enumerable properties of an object. However:
var i = 0;
for (var propertyName in window) {
i++;
}
returns a count of 177.
Why is this different? Shouldn't they both only be returning the count of enumerable properties?
keys() The Object. keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique. There is a good thread on Stack Overflow on this topic. (It is titled with 'associative array', but it really is about a JS Object).
keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually. You get an array of strings, because Property names are strings by definition.
for-in
loops over the object's own enumerable properties and the enumerable properties of its prototype (and its prototype, etc.). Object.keys
only lists the object's own enumerable properties.
So Object.keys
builds an array something like this:
var keys = [];
var key;
for (key in object) {
if (object.hasOwnProperty(key)) { // But using an internal, non-overrideable
// operation, not literally the method
keys.push(key);
}
}
Note the hasOwnProperty
check (it's not really a call to the method, it's an internal check that can't be tricked by replacing the method or similar).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With