I was trying to get/count properties of an object and found this QaA, and this cross-browser solution.
However, Object.keys
does not always return the same as with for-in loop
.
var obj = {foo: "foo", bar: "bar"};
// foo, bar
console.log(Object.keys(obj));
// foo, bar
for(var p in obj) {
console.log(p);
}
var obj = document.body.style;
// [] <-- empty array
console.log(Object.keys(obj));
// background, backgroundImage, border, fontFamily...
for(var p in obj) {
console.log(p);
}
I'm not sure if objects like document.body.style
are enumerable
.
Even if they are, according to Mozilla, we can use Object.getOwnPropertyNames
instead for none-enumerable properties, but it returns an empty array as well.
Can someone explain this? And is it possible to get all properties of objects like document.body.style
without for-in loop?
edit
Oops, I was testing this with Firefox only. Until Osiris posts a comment, I realized this only happens to Firefox (19 and 20 which is the latest version). IE 9, Opera 12, Chrome 26, Safari 5 are all fine.