JavaScript通过NodeList进行迭代 [英] JavaScript iterate through NodeList
问题描述
我正在寻找一种遍历NodeList的最佳方法(不包括长度).我正在使用:
I am looking for a best way to iterate through NodeList excluding length. I am using:
var foo = document.querySelectorAll('[id^=foo_id]')
console.log(foo)
返回的NodeList具有所有必需的元素以及最后一个长度为length的条目.
Returned NodeList has all the required elements + the last entry of length:.
0: input#foo_id_...
1: input#foo_id_...
..................
n: input#foo_id_...
length: n+1
我想知道哪种最有效的方法来迭代该NodeList.我可以利用列表长度等,但是想知道是否还有更优雅"的方式.
I wonder what the most efficient way to iterate through that NodeList. I can utilize list length etc, but would like to know if there is a more "elegant" way.
推荐答案
最简单的方法是for
循环:
for (let i = 0; i < foo.length; i++) {
// Do stuff
}
这是最好的解决方案,如此处所述,使用数组方法或将NodeList转换为数组-如果需要,可以使用其他变量,但是for
循环只需要在NodeList上循环即可. (感谢异端猴子向我指出了这一点.)
This is the best solution, as pointed out here it's bad practice to use array methods or convert a NodeList to an array - use a different variable if you need to, but a for
loop is all you need to loop over a NodeList. (Thanks Heretic Monkey for pointing this out to me).
如果要使用forEach
,map
等数组方法,则最好先转换为数组-扩展非常简单:
If you want to use array methods like forEach
, map
, etc., it's best convert to an array first - this is incredibly simple with spreading:
[...foo].forEach(e /* Do stuff */);
如果要专门使用map
,请使用Array.from
作为第二个参数是要应用于map
的回调.
If you want to specifically use map
, use Array.from
as the second argument is the callback to be applied to map
.
Array.from(foo, e => /* .map callback */);
在较旧的环境中:
Array.prototype.slice.call(foo).forEach(e => /* Do stuff */);
(我知道您可以在NodeList上使用数组方法,但是如果坚持使用一种数据类型会更容易.)
这篇关于JavaScript通过NodeList进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!