Object.keys() 在 Internet Explorer 9 中适用于内置对象吗?
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 JavaScript 中,有本机对象和宿主对象。一般来说,您可以依赖诸如
Object.keys
之类的东西来处理本机对象,但不能用于主机对象。window
、document
等都是宿主对象。 IE 尤其以其宿主对象与本机不同而闻名(宿主函数没有call
或apply
功能等)。当然,也可能是
document
没有可枚举属性。对象的大多数默认属性都是不可枚举的,因此不会显示在Object.keys
中。例如,Object.keys([]).length
和Object.keys(new RegExp(".*")).length
都是0
因为它们都没有任何可枚举属性,即使它们都有很多属性(它们具有所有“方法”的属性,当然空白数组有一个长度
属性和RegExp
有lastIndex
属性)。更新:事实上,这是可枚举的事情。尝试这个测试:
对我来说,在 IE9 上,这些警报分别是“0”和“1”。所以
window.document
支持Object.keys
,只是window.document
默认情况下没有任何可枚举< /em> 属性。 (相比之下,在 Chrome 上,我首先获得 65 个可枚举属性,当然,一旦添加了扩展,我就获得了 66 个属性。)这是一个更完整的测试页面 (Live Copy)(快速拼凑在一起,不美观):
In JavaScript, there are native objects and host objects. In general, you can rely on things like
Object.keys
working with native objects, but not with host objects.window
,document
, and others are host objects. IE in particular is well-known for its host objects not being native-like (host functions don't have thecall
orapply
feature, etc.).Alternately, of course, it could be that
document
has no enumerable properties. Most of the default properties of objects are non-enumerable and so don't show up inObject.keys
. For instance,Object.keys([]).length
andObject.keys(new RegExp(".*")).length
are both0
because neither has any enumerable properties even though they both have lots of properties (they have properties for all of their "methods", and of course the blank array has alength
property and theRegExp
has alastIndex
property).Update: And in fact, it was the enumerable thing. Try this test:
For me, on IE9, those alerts are "0" and "1", respectively. So
window.document
supportsObject.keys
, it's just thatwindow.document
doesn't, by default, have any enumerable properties. (In contrast, on Chrome I get 65 enumerable properties to start with, and of course 66 once I've added my expando.)Here's a rather more full test page (live copy) (hacked-together quickly, not a thing of beauty):