Iterate over defined elements of a JS array

Posted by sibidiba on Stack Overflow See other posts from Stack Overflow or by sibidiba
Published on 2011-01-12T17:22:24Z Indexed on 2011/01/12 17:53 UTC
Read the original article Hit count: 160

Filed under:
|

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:

for (var item in map) {...}

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.

var length = map.lenth;
for (var i = 0; i < length; i++) {
  var item = map[i];
  ...
}

does work but just like

$.each(map, function(index, item) {...});

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

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

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)?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery