What's the best way to loop through a set of elements in JavaScript?

前端 未结 14 2018
清歌不尽
清歌不尽 2020-11-27 06:34

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

        
14条回答
  •  清歌不尽
    2020-11-27 07:03

    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);
    }
    

    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 Update

    for...of gives you the name but not the index, available since ES6

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

提交回复
热议问题