JavaScript Object.keys()方法替代与IE8的兼容性 [英] JavaScript Object.keys() method alternative for compatibility with IE8

查看:161
本文介绍了JavaScript Object.keys()方法替代与IE8的兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在IE8中测试不支持Object方法时遇到错误。我正在使用 Object.keys()

I'm getting in error when testing in IE8 that the Object method is not supported. I'm using Object.keys()

Object.keys(jsoncont).sort(function(a,b){
   return b.localeCompare(a)
 }).forEach(function(key) {
    var val = jsoncont[key];

   /* My code here */
 });
}

IE8是否支持这种方法?

Is there a good workaround for this method that is supported by IE8?

推荐答案

Mozilla解释了如何在旧浏览器中填充该功能: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Mozilla has an explanation of how to polyfill the function in older browsers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

// 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;
    };
  }());
}

这篇关于JavaScript Object.keys()方法替代与IE8的兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆