/ Published in: JavaScript
We are setting up two variables. The assignment in the middle part of the for loop is also tested for truthfulness — if it succeeds, the loop continues. Since i is incremented each time, items from the array will be assigned to item in sequential order. The loop stops when a "falsy" item is found (such as undefined).
Note that this trick should only be used for arrays which you know do not contain "falsy" values (arrays of objects or DOM nodes for example). If you are iterating over numeric data that might include a 0 or string data that might include the empty string you should use a standard for loop.
Note that if someone added new properties to Array.prototype, using a "for...in" loop is no option since the loop will also iterate over the new prototype properties.
Note that this trick should only be used for arrays which you know do not contain "falsy" values (arrays of objects or DOM nodes for example). If you are iterating over numeric data that might include a 0 or string data that might include the empty string you should use a standard for loop.
Note that if someone added new properties to Array.prototype, using a "for...in" loop is no option since the loop will also iterate over the new prototype properties.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
for (var i = 0, item; item = a[i++];) { // Do something with item }
URL: https://developer.mozilla.org/en/A_re-introduction_to_JavaScript#Arrays