使用什么而不是Object.keys()?

时间:2013-07-23 18:41:19

标签: jquery

我需要在Jquery中找到可以在IE8和真实浏览器中运行的东西。我是Jquery的新手,以下是我在现代浏览器中运行的代码:

$('#FIELD_'+office_id).on('change',function(){
    offices = $(this).val();
for(var i=0; i<=Object.keys(southland.address).length;i++){
        if(offices == Object.keys(southland.address)[i]){
            address = southland.address[offices]Object.keys(southland.address[offices])[0]];
        }
    }

其中southland.address来自外部数组。这在Chrome,IE10和FF中是完美的,我能为IE8做些什么吗?

1 个答案:

答案 0 :(得分:10)

要在旧版浏览器中支持Object.keys,您可以使用以下代码段:

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

或此polyfill(包括其他垫片):

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