I have stumbled into several methods of looping in JavaScript, what I like the most is:
for(var i = 0; i < a.length; i++){
var element = a[i];
}
Just store the length in a variable first.
var len = a.length;
for (var i = 0; i < len; i++) {
var element = a[i];
}
If you have many elements in the array and speed is an issue then you want to use a while loop that iterates from highest to lowest.
var i = a.length;
while( --i >= 0 ) {
var element = a[i];
// do stuff with element
}
I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:
function createIterator(x) {
var i = 0;
return function(){
return x[i++];
};
}
Then to use:
var iterator=createIterator(['a','b','c','d','e','f','g']);
iterator();
returns "a";
iterator();
returns "b";
and so on.
To iterate the whole list and display each item:
var current; while(current=iterator()) { console.log(current); }
Be aware that the above is only acceptable for iterating a list that contains "non-falsy" values. If this array contained any of:
the previous loop would stop at that item, not always what you want/expect.
To avoid this use:
var current;
while((current=iterator())!==undefined)
{
console.log(current);
}