【问题标题】:How can I enumerate through Javascript objects like HTMLElement? [duplicate]如何通过 HTMLElement 之类的 Javascript 对象进行枚举? [复制]
【发布时间】:2014-06-24 12:35:58
【问题描述】:

我想枚举所有全局对象。这包括 HTMLElement、SVGAnimatedPreserveAspectRatio 和 CameraControl。我为这个问题看到的所有答案都让您遍历windowglobal 对象(通过命名空间外的this 等技巧获得)。然而,这些技巧并没有列出元素,即使它包含在 window!

这是一些控制台日志,但如果你把它放在一个测试 .html 页面中,你会得到相同的结果。

> HTMLElement
[object Function]
> window['HTMLElement']
[object Function]
> 'HTMLElement' in window
true
> for(var name in window){if(name == "HTMLElement")console.log('Found it!');}
undefined
> for(var name in window){if(name == "sessionStorage")console.log('Found it!');}
"Found it!"

如何枚举所有全局对象?

【问题讨论】:

  • var a = Object.getOwnPropertyNames(window); -> a.indexOf("HTMLElement") -> 475(对我来说)

标签: javascript dom


【解决方案1】:

您可以像这样遍历所有全局对象:

var arr = Object.getOwnPropertyNames(window);
for(var i = 0; i < arr.length; i++){
   window[arr[i]]; // do something
}

【讨论】:

    猜你喜欢
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2012-01-14
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多