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

前端 未结 14 1787
清歌不尽
清歌不尽 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条回答
  • I know that you don't want to hear that, but: I consider the best practice is the most readable in this case. As long as the loop is not counting from here to the moon, the performance-gain will not be uhge enough.

    0 讨论(0)
  • 2020-11-27 07:14

    Form of loop provided by Juan Mendez is very useful and practical, I changed it a little bit, so that now it works with - false, null, zero and empty strings too.

    var items = [
        true,
        false,
        null,
        0,
        ""
    ];
    
    for(var i = 0, item; (item = items[i]) !== undefined; i++)
    {
        console.log("Index: " + i + "; Value: " + item);
    }
    
    0 讨论(0)
提交回复
热议问题