title: Javascript iterating through sparse array
body: <p>I have a sparse array (indexes are not consecutive) like this:</p>
  
  <pre><code>var testArray = { 0: "value1", 5: "value2", 10: "value3", 15: "value4" };
  </code></pre>
  
  <p>I would simply like to iterate through each item, do some stuff, and be able to break under a certain condition. </p>
  
  <p>I am fairly new to Javascript and I didn't find a proper way to do it. Here is what I tried:</p>
  
  <ol>
  <li><p>Built-in "for..in". It seems that this is <a href="https://stackoverflow.com/questions/500504/javascript-for-in-with-arrays">not the correct way to iterate through an array</a></p></li>
  <li><p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach" rel="nofollow noreferrer">forEach</a> from ECMASCRIPT5. This one iterate correctly, but I cannot break from the loop.</p></li>
  <li><p><a href="http://documentcloud.github.com/underscore/#each" rel="nofollow noreferrer">_.each()</a> from Underscore.js. Same result as #2.</p></li>
  <li><p><a href="http://api.jquery.com/jQuery.each/" rel="nofollow noreferrer">$.each()</a> from JQuery. With this one I can break by returning false, but it won't iterate correctly. For the above example, instead of iterating at 0, 5, 10, 15, it will iterate at 0,1,2,3,4,5,6... which is obviously not what I expect.</p></li>
  </ol>
  
  <p>So my question is: <strong>Is there an easy way to iterate a sparse array with the possibility to break during the loop in Javascript or would it be better to use another data structure like an hashtable? If so, any recommandation?</strong></p>
  
  <p>Thanks!   </p>