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);
}
答案 0 :(得分:4)
在JavaScript中,有本机对象和主机对象。通常,您可以依赖Object.keys
使用本机对象,但不能使用宿主对象。 window
,document
和其他人是主持人对象。特别是IE因其主机对象不是本机的而众所周知(主机功能没有call
或apply
功能等。)
或者,当然,document
可能没有可枚举的属性。对象的大多数默认属性都是不可枚举的,因此不会显示在Object.keys
中。例如,Object.keys([]).length
和Object.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.document
支持Object.keys
,默认情况下window.document
没有可枚举的属性。 (相比之下,在Chrome上我开始使用65个可枚举的属性,当然我添加了我的expando后有66个。)
这是一个相当完整的测试页面(live copy)(很快就被黑了,而不是美丽的东西):
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;
}
};