2

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.

Community
  • 1
  • 1
user1643156
  • 3,657
  • 10
  • 34
  • 58

2 Answers2

0

The properties of document.body.style are not enumerable in Firefox. You can easily test that using:

document.body.style.propertyIsEnumerable('background'); // FF: false, WebKit: true
David Hellsing
  • 97,234
  • 40
  • 163
  • 203
0

It depends on what kind of properties you want to count.

for...in

Iterates through all enumerable properties of an object including properties found in the prototype chain.

Object.keys

Returns all enumerable properties that can be found directly upon the object. Does not consider properties of the prototype chain.

Object.getOwnPropertyNames

returns all properties, enumerable or not, that can be found directly upon the object. Does not consider properties of the prototype chain.

Depending on the object, those methods can, of course, return different results. What makes this even more complicated is that objects (or prototypes) may have properties that are enumerable in one browser and not in the other.

a better oliver
  • 24,069
  • 2
  • 48
  • 59
  • As for objects like `document.body.style`, it doesn't matter which method I use, all three methods should return some properties while all other browsers do. I believe this is a bug (it's not fixed till version 20). – user1643156 Apr 23 '13 at 10:57
  • I'd say it's not specified, but can be regarded as a bug. That aside, if your only concern is `document.body.style` you should be free choose between all three, that's right. – a better oliver Apr 23 '13 at 11:10