What to use instead of Object.keys()?

前端 未结 1 1614
醉梦人生
醉梦人生 2021-01-12 21:59

I need to find something in Jquery that can work in IE8 as well as real browsers. I\'m brand new to Jquery, the following is my code that works in modern browsers:



        
相关标签:
1条回答
  • 2021-01-12 22:37

    To support Object.keys in older browsers, you can use this snippet:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Compatibility

    if (!Object.keys) {
      Object.keys = (function () {
        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 = [];
    
          for (var prop in obj) {
            if (hasOwnProperty.call(obj, prop)) result.push(prop);
          }
    
          if (hasDontEnumBug) {
            for (var i=0; i < dontEnumsLength; i++) {
              if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
            }
          }
          return result;
        };
      })();
    }
    

    or this polyfill (which includes other shims, as well):

    https://github.com/kriskowal/es5-shim/

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