Object.keys not working in internet Explorer

后端 未结 2 897
盖世英雄少女心
盖世英雄少女心 2020-12-08 10:30

I have a program to return a list of keys from dictionary. The Code works correctly in Chrome, Opera and Firefox but not Internet Explorer. I have added alert comments to cl

相关标签:
2条回答
  • 2020-12-08 11:09

    Object.keys is not avaiable in IE < 9. As a simple workaround you could use:

    if (!Object.keys) {
      Object.keys = function(obj) {
        var keys = [];
    
        for (var i in obj) {
          if (obj.hasOwnProperty(i)) {
            keys.push(i);
          }
        }
    
        return keys;
      };
    }
    

    Here is a more comprehensive polyfill:

    // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
    if (!Object.keys) {
      Object.keys = (function () {
        'use strict';
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
            dontEnums = [
              'toString',
              'toLocaleString',
              'valueOf',
              'hasOwnProperty',
              'isPrototypeOf',
              'propertyIsEnumerable',
              'constructor'
            ],
            dontEnumsLength = dontEnums.length;
    
        return function (obj) {
          if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
            throw new TypeError('Object.keys called on non-object');
          }
    
          var result = [], prop, i;
    
          for (prop in obj) {
            if (hasOwnProperty.call(obj, prop)) {
              result.push(prop);
            }
          }
    
          if (hasDontEnumBug) {
            for (i = 0; i < dontEnumsLength; i++) {
              if (hasOwnProperty.call(obj, dontEnums[i])) {
                result.push(dontEnums[i]);
              }
            }
          }
          return result;
        };
      }());
    }
    
    0 讨论(0)
  • 2020-12-08 11:09

    Alternatively if you have access to lodash you can use keys. e.g.

    _.keys(yourObj);

    0 讨论(0)
提交回复
热议问题