Object.keys无法在Internet Explorer中工作

Pet*_*ton 22 javascript internet-explorer

我有一个程序来从字典中返回一个键列表.该代码在Chrome,Opera和Firefox中正常运行,但在Internet Explorer中无法运行.我已添加警报注释以关闭问题所在.以下是导致问题的代码.警报显示在订单中

  • 应用初始化
  • 获得JSON
  • 得到了JSON
  • 得到密钥(不在IE中显示)

我在这里找到了一个类似的问题,但我相信这个例子,这不是正确的问题,因为我创建了字典,因此它是一个本机对象.

我不再确定Object.keys是否存在问题所以这里是指向整页的链接.我在页面中使用JavaScript以便于查看

http://www.londonlayout.co.uk/dev/live.htm

 var myApp = {
    init: function () {
        var def = $.Deferred();
        alert('App Initializing');
        $.getJSON('data/data.json', function (raw) {
            alert('Getting JSON');
            myApp.data = raw;
            $.each(myApp.data, function (code, details) {
                try {
                    myApp.nameDict[details.name] = code;
                }
                catch (e) {}
            });
            alert('Got JSON');
            myApp.names = Object.keys(myApp.nameDict);
            alert('Got Keys')
            def.resolve();
        });
        return def.promise();
    },
    data: {},
    nameDict: {}
}
Run Code Online (Sandbox Code Playgroud)

jab*_*lab 78

Object.keys不是在IE <9缴费.作为一个简单的解决方法,您可以使用:

if (!Object.keys) {
  Object.keys = function(obj) {
    var keys = [];

    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        keys.push(i);
      }
    }

    return keys;
  };
}
Run Code Online (Sandbox Code Playgroud)

这是一个更全面的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;
    };
  }());
}
Run Code Online (Sandbox Code Playgroud)

  • @PeterSaxton因为垫片的性能可能远低于原生版本. (3认同)