用什么代替Object.keys()? [英] What to use instead of Object.keys()?

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

问题描述

我需要在Jquery中找到可以在IE8和实际浏览器中运行的功能.我是Jquery的新手,以下是我的代码在现代浏览器中的工作原理:

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:

$('#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做任何事情吗?

where southland.address comes from an external array. This works perfect in Chrome, IE10 and FF, anything I can do for IE8?

推荐答案

要在较旧的浏览器中支持Object.key,可以使用以下代码段:

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

https://developer. mozilla.org/zh-CN/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(也包括其他垫片):

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

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

这篇关于用什么代替Object.keys()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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