3

Object.keys() 方法适用于我,代码如下:

var foo = {foo: 1, bar: 2};
console.log(Object.keys(foo).length);

然而,Object.keys() 为内置对象返回一个长度为零的数组,代码如下:

<!doctype html> 
<html>

<head>

<title>Object.keys()</title>

</head>

<body>
<script type="text/javascript">
console.log(Object.keys(window.document).length);
</script>

</body>

</html>

我错过了什么吗?我正在使用 Internet Explorer 9.0.8112.16421。


后记:我仍然不清楚为什么会这样(例如):

    for (prop in performance.timing) {
        if (performance.timing.hasOwnProperty(prop)) {
            console.log(prop); 
        }
    }

...在 IE9 中不产生任何结果,而这工作正常:

for (prop in performance.timing) {
    console.log(prop); 
}
4

1 回答 1

5

在 JavaScript 中,有原生对象宿主对象。通常,您可以依赖诸如Object.keys使用本机对象之类的东西,但不能使用宿主对象。window, document, 和其他是宿主对象。尤其是 IE,它的宿主对象不是原生的(宿主函数没有callorapply特性等)而闻名。

或者,当然,它可能document没有可枚举的属性。对象的大多数默认属性都是不可枚举的,因此不会出现在Object.keys. 例如,Object.keys([]).lengthObject.keys(new RegExp(".*")).length都是0因为它们都没有任何可枚举的属性,即使它们都有很多属性(它们的所有“方法”都有属性,当然空白数组有一个length属性,而空白数组也RegExp有一个lastIndex属性)。


更新:事实上,这是可数的事情。试试这个测试:

alert(Object.keys(window.document).length);
window.document.AAA__expando__property = "foo";
alert(Object.keys(window.document).length);

对我来说,在 IE9 上,这些警报分别是“0”和“1”。所以window.documentsupports Object.keys,只是window.document默认情况下没有任何可枚举的属性。(相比之下,在 Chrome 上,我一开始就有 65 个可枚举属性,当然,一旦我添加了我的 expando,就有 66 个。)

这是一个更完整的测试页面(实时副本)(快速组合在一起,而不是美丽的东西):

window.onload = function() {

  document.getElementById('theButton').onclick = function() {

    if (typeof Object.keys !== 'function') {
      display("<code>Object.keys</code> is not a function");
      return;
    }
    showKeys("Before adding", Object.keys(window.document));
    window.document.AAAA__expando__foo = "bar";
    showKeys("After adding", Object.keys(window.document));
  };

  function showKeys(prefix, keys) {
    var p, ul;

    keys.sort();
    prefix =
      "[" + prefix +
      "] Keys on <code>window.document</code> (" +
      keys.length +
      ")";
    if (keys.length !== 0) {
      prefix += " (click to toggle list)";
    }
    p = display(prefix);
    if (keys.length !== 0) {
      ul = document.createElement("ul");
      ul.innerHTML = "<li>" + keys.join("</li><li>") + "</li>";
      ul.style.display = "none";
      document.body.appendChild(ul);
      p.onclick = function() {
        ul.style.display =
          (ul.style.display === "none") ? "" : "none";
      };
    }
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
    return p;
  }

};
于 2011-06-15T11:11:55.733 回答