Sunday, April 15, 2012

Javascript - Object.keys Browser Compatibility

For Object.keys compatibility in all browsers add this code before using Object.keys.

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
  return k;
}

You can now use Object.keys as normal such as Object.keys(myObject).length
Anonymous said...

Why are you doing Object.prototype.hasOwnProperty.call(o,p) instead of a simple o.hasOwnProperty(p)? Is it just in case that method is overridden in o?

Craig Constable said...

From memory o.hasOwnProperty(p) does not work correctly in IE < 9

Unknown said...

Hi,

Which information given by you on JavaScript-Browser Compatibility, very informative. So thanks for sharing your

knowledge. There are few other link that's also helpful for developers.


http://www.mindstick.com/Articles/643c4797-cd25-4dce-ac35-8107a88e3f0c/?JavaScript%20Browser%20Compatibility
http://www.tutorialspoint.com/javascript/javascript_browsers_handling.htm

Anonymous said...

thanks alot...

Anonymous said...

I don't believe for in loops work in IE8, so while this should solve the issue theoretically, it may introduce another problem.

Sam R said...

@garvan - for-in was added in Internet Explorer 5.
http://tokenposts.blogspot.com.au/2012/04/javascript-objectkeys-browser.html

Wahyoe said...

User

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

explorer 5 had been not a lot of help

Post a Comment