Object.keys在IE11中工作的解决方法是什么?

时间:2019-05-16 15:53:57

标签: javascript arrays object internet-explorer

我正在尝试使用在Object.keys for IE8上找到的以下功能

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(o) {
    if (typeof o != "object" && typeof o != "function" || o === null)
      throw new TypeError("Object.keys called on a non-object");

    var result = [];
    for (var name in o) {
      if (hasOwnProperty.call(o, name))
        result.push(name);
    }

    if (hasDontEnumBug) {
      for (var i = 0; i < DontEnumsLength; i++) {
        if (hasOwnProperty.call(o, DontEnums[i]))
          result.push(DontEnums[i]);
      }
    }

    return result;
  };
})();

这是我尝试实现的方式:

var attributeCodeTextLength = Object.keys(item.versionRoomTypeAttributeList[0].attributeCode).length;
var attributeLimit = 7;
if (Object.keys(item.versionRoomTypeAttributeList[0].attributeCode).length > 2) {
  attributeLimit = 5;
  if (Object.keys(item.versionRoomTypeAttributeList[0].attributeCode).length > 3) {
    attributeLimit = 4;
  }
}

但是我不断收到以下错误:

TypeError: Object.keys: argument is not an Object

1 个答案:

答案 0 :(得分:-1)

这是我发现可以正常使用的Polyfill

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

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

  return keys;
};