简体   繁体   中英

Why are Object.keys() and for … in different?

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM