Iterating Arrays
The most common way to loop through the elements of an array is
with a for loop (for):
varkeys=Object.keys(o);// Get an array of property names for object ovarvalues=[]// Store matching property values in this arrayfor(vari=0;i<keys.length;i++){// For each index in the arrayvarkey=keys[i];// Get the key at that indexvalues[i]=o[key];// Store the value in the values array}
In nested loops, or other contexts where performance is critical, you may sometimes see this basic array iteration loop optimized so that the array length is only looked up once rather than on each iteration:
for(vari=0,len=keys.length;i<len;i++){// loop body remains the same}
These examples assume that the array is dense and that all
elements contain valid data. If this is not the case, you should test
the array elements before using them. If you want to exclude null, undefined, and nonexistent elements, you can
write this:
for(vari=0;i<a.length;i++){if(a[i]===null||a[i]===undefined)continue;// Skip null, undefined,// and nonexistent elements// loop body here}
If you only want to skip undefined and nonexistent elements, you might write:
for(vari=0;i<a.length;i++){if(a[i]===undefined)continue;// Skip undefined + nonexistent elements// loop body here}
Finally, if you only want to skip indexes for which no array element exists but still want to handle existing undefined elements, do this:
for(vari=0;i<a.length;i++){
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access