在 JavaScript 中循环一组元素的最佳方法是什么? [英] What's the best way to loop through a set of elements in JavaScript?

查看:31
本文介绍了在 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...of 为您提供名称但不提供索引,自 ES6

for (const item of list) {
    console.log("Looping: index ", "Sorry!!!", "item" + item);
}

这篇关于在 JavaScript 中循环一组元素的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆