Wednesday, July 7, 2010

Get length of associative arrays in Javascript

When you make an associative array in Javascript, it is not that straightforward to get the length of the array. Example:
Code:
  1. var ar = new Array();
  2. ar['nice'] = "hello";
  3. alert(ar.length);
  4. //keeps on giving zero

This is because associative arrays are treated like objects and hence they do not have the "length" attribute. To traverse through the array, you can use this:
Code:
  1. var ar_ct = 0;
  2. var ar = new Array();
  3. ar['nice'] = "hello";
  4. for (i in ar)
  5. {
  6. alert(ar[i]); // value is "hello"
  7. }

No comments:

Post a Comment