遍历JavaScript中的一组元素的最佳方法是什么? [英] What's the best way to loop through a set of elements in JavaScript?
问题描述
在过去以及我目前的大多数项目中,我倾向于使用如下所示的for循环:
In the past and with most my current projects I tend to use a for loop like this:
var elements = document.getElementsByTagName('div');
for (var i=0; i<elements.length; i++) {
doSomething(elements[i]);
}
我听说使用反向while"循环更快,但是我没有真正的方法来确认这一点:
I've heard that using a "reverse while" loop is quicker but I have no real way to confirm this:
var elements = document.getElementsByTagName('div'),
length = elements.length;
while(length--) {
doSomething(elements[length]);
}
当循环遍历JavaScript中的元素或与此相关的任何数组时,什么是最佳实践?
What is considered as best practice when it comes to looping though elements in JavaScript, or any array for that matter?
推荐答案
这是我经常使用的一种不错的循环形式.您可以通过for语句创建迭代变量,而无需检查length属性,这在通过NodeList进行迭代时特别昂贵.但是,您必须小心,如果数组中的任何值都可能是虚假" ,则您不能使用它.实际上,我仅在遍历不包含空值的对象数组(例如NodeList)时使用它.但是我喜欢它的语法糖.
Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, you must be careful, you can't use it if any of the values in array could be "falsy". In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar.
var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];
for (var i=0, item; item = list[i]; i++) {
// Look no need to do list[i] in the body of the loop
console.log("Looping: index ", i, "item" + item);
}
请注意,这也可以用于向后循环(只要您的列表没有 ['-1']
属性)
Note that this can also be used to loop backwards (as long as your list doesn't have a ['-1']
property)
var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];
for (var i = list.length - 1, item; item = list[i]; i--) {
console.log("Looping: index ", i, "item", item);
}
ES6更新
for (let item of list) {
console.log("Looping: index ", "Sorry!!!", "item" + item);
}
这篇关于遍历JavaScript中的一组元素的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!