Object.keys, polyfill and older browsers

After some headbanging on the IE compatibility wall I found that Object.keys doesnt work in older browsers. Which may be common knowledge to many, but not me until now.

I tried to work around it with a s.k. polyfill. This code is for IE8 and is working as it isnt giving any errors:

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

However when I try to use the Object.keys… further down in code:

Object.keys(elementValues).forEach(function (element) {


It stops on the .forEach… and gives the error. "“Object doesn’t support property or method ‘forEach’”
My question is: which functions or methods is available when polyfill is used? And is there any documentation of this “workaround”?
Furthermore I would be glad if you could help me with a workaround for this particular problem. The code look like this:

                    if (!Object.keys)
                    Object.keys = function(obj) {
                        if (obj !== Object(obj))
                            throw new TypeError('Object.keys called on a non-object');
                        var k = [], p;
                        for (p in obj) if (Object.prototype.hasOwnProperty.call(obj, p)) k.push(p);
                            return k;
                    };
                
                Object.keys(elementValues).forEach(function (element) {
                    var checked = elementValues[element];
                    $("#" + element).prop('checked', checked);
                });

that means that your IE does not only not support Object.keys() (therefore you polyfilled it), it additionally doesn’t support Array.forEach() either. you could polyfill that as well.

PS. MDN lists polyfills for almost all new methods.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.