The Object.keys() method works fine for me with code like this:
var foo = {foo: 1, bar: 2};
console.log(Object.keys(foo).length);
However, Object.keys() returns a zero-length array for built-in objects with code like this:
<!doctype html>
<html>
<head>
<title>Object.keys()</title>
</head>
<body>
<script type="text/javascript">
console.log(Object.keys(window.document).length);
</script>
</body>
</html>
Am I missing something? I’m using Internet Explorer 9.0.8112.16421.
Postscript: I’m still not clear why this (for example):
for (prop in performance.timing) {
if (performance.timing.hasOwnProperty(prop)) {
console.log(prop);
}
}
…produces nothing in IE9, whereas this works fine:
for (prop in performance.timing) {
console.log(prop);
}
In JavaScript, there are native objects and host objects. In general, you can rely on things like
Object.keysworking with native objects, but not with host objects.window,document, and others are host objects. IE in particular is well-known for its host objects not being native-like (host functions don’t have thecallorapplyfeature, etc.).Alternately, of course, it could be that
documenthas no enumerable properties. Most of the default properties of objects are non-enumerable and so don’t show up inObject.keys. For instance,Object.keys([]).lengthandObject.keys(new RegExp(".*")).lengthare both0because neither has any enumerable properties even though they both have lots of properties (they have properties for all of their “methods”, and of course the blank array has alengthproperty and theRegExphas alastIndexproperty).Update: And in fact, it was the enumerable thing. Try this test:
For me, on IE9, those alerts are “0” and “1”, respectively. So
window.documentsupportsObject.keys, it’s just thatwindow.documentdoesn’t, by default, have any enumerable properties. (In contrast, on Chrome I get 65 enumerable properties to start with, and of course 66 once I’ve added my expando.)Here’s a rather more full test page (live copy) (hacked-together quickly, not a thing of beauty):