Iterate over defined elements of a JS array
<p>I'm using a JS array to Map IDs to actual elements, i.e. a key-value store. I would like to iterate over all elements. I tried several methods, but all have its caveats:</p>

<pre><code>for (var item in map) {...}
</code></pre>

<p>Does iterates over all properties of the array, therefore it will include also functions and extensions to Array.prototype. For example someone dropping in the Prototype library in the future will brake existing code.</p>

<pre><code>var length = map.lenth;
for (var i = 0; i &lt; length; i++) {
  var item = map[i];
  ...
}
</code></pre>

<p>does work but just like </p>

<pre><code>$.each(map, function(index, item) {...});
</code></pre>

<p>They iterate over the whole range of indexes 0..max(id) which has horrible drawbacks:</p>

<pre><code>var x = [];
x[1]=1;
x[10]=10;
$.each(x, function(i,v) {console.log(i+": "+v);});

0: undefined
1: 1
2: undefined
3: undefined
4: undefined
5: undefined
6: undefined
7: undefined
8: undefined
9: undefined
10: 10
</code></pre>

<p>Of course my IDs wont resemble a continuous sequence either. Moreover there can be huge gaps between them so skipping undefined in the latter case is unacceptable for performance reasons. How is it possible to safely iterate over only the defined elements of an array (in a way that works in all browsers and IE)?</p>
