Javascript 的“for in”应该是这样吗?构造迭代长度属性?
我正在制作一个小书签,但我在 IE8 中遇到了一些奇怪的行为。导致问题的代码是这样的:
var els = document.getElementById("my_id").getElementsByTagName("*");
for(var i in els)
{
alert(i+","+els[i])
}
首先发出警报的是“length, n”。在 chrome 中并非如此:仅在 IE8 中如此。
有趣的是,它的行为似乎有所不同,具体取决于代码是否位于控制台/地址栏或页面本身。
这是标准行为吗?
编辑:
也不是我运行它的网站。 getElementsByTagName
是否有可能返回一个在 IE 中设置有 "length"
键的数组?它当然不会返回纯数组。
I'm making a bookmarklet, but I've encountered some wierd behaviour in IE8. The code causing the problem is this:
var els = document.getElementById("my_id").getElementsByTagName("*");
for(var i in els)
{
alert(i+","+els[i])
}
The first thing that is alerted is "length, n". This isn't the case in chrome: just in IE8.
Interestingly, it seems to behave differently depending on whether the code goes in the console/address bar or the page itself.
Is this standard behaviour?
EDIT:
Not down to the website that I run it on either. Is it possible that getElementsByTagName
returns an array with a "length"
key set in IE? It certainly doesn't return a pure array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是我迭代列表的方法。这样,您就不必在循环中编写额外的行,例如
var el = els[i]
。Here's how I iterate over lists. This way, you won't have to write an extra line in the loop, such as
var el = els[i]
.除非您为 NodeList 定义自己的迭代器(仅限 JavaScript (Mozilla))。 [这是我为 js-iterators 存储库创建的一个实现]。
Not unless you define your own iterator for
NodeList
s, which is JavaScript (Mozilla)-only. [Here's an implementation] of one I have created for my js-iterators repo.将对象(如节点列表、参数对象或自定义对象)转换为其成员数组的方法通常很有用。
A method to convert an object, like a node list, arguments object, or custom object to an array of its members is often useful.
你得到的不是一个数组,而是一个nodeList。
请参阅此处,单击链接“getElementsByTagName('element_name')”
此外,无论如何,for..in 并不意味着用于迭代数组。用于
数组迭代。
可以使用 获取元素。
对于节点列表,如果您想“正确”地执行操作,则
What you get is not an array, it is a nodeList.
See here, click the link "getElementsByTagName('element_name')"
Furthermore, for..in is not meant to be used for iterating over an array anyway. Use
for array iteration.
For a nodelist, you can get the element with
if you want to do it "right".
IE 的行为是正确的。它可能会返回各种奇怪的东西,因为
for .. in
会迭代对象的所有成员名称。getElementsByTagName
返回一个NodeList
,并且NodeList
的属性在 DOM 标准:长度
和 <代码>项目(i)。大多数 JavaScript 实现也允许[i]
。因此,您应该编写以下内容:
The IE behavior is correct. It may return all kinds of weird stuff, since
for .. in
iterates over all member names of the object.getElementsByTagName
returns aNodeList
, and the properties of aNodeList
are specified in the DOM standard:length
anditem(i)
. Most JavaScript implementations will also allow[i]
.Therefore, you should write the following:
除了枚举对象的属性之外,请勿将
for..in
用于任何其他用途(除非您喜欢惊喜!)只需对数组和节点列表使用简单的 for 循环。Do not use
for..in
for anything other than enumerating properties of an object (unless you like surprises!) Just use a simple for loop for arrays and nodelists.