12

Possible Duplicate:
Length of Javascript Associative Array

I want to check the length of a multidimensional array but I get "undefined" as the return. I'm assuming that I am doing something wrong with my code but I can't see anything odd about it.

alert(patientsData.length); //undefined
alert(patientsData["XXXXX"].length); //undefined
alert(patientsData["XXXXX"]['firstName']); //a name

fruits = ["Banana", "Orange", "Apple", "Mango"];
alert(fruits.length); //4

Thoughts? Could this have something to do with scope? The array is declared and set outside of the function. Could this have something to do with JSON? I created the array from an eval() statement. Why does the dummy array work just fine?

Community
  • 1
  • 1
BFTrick
  • 5,211
  • 6
  • 24
  • 28

3 Answers3

12

Those are not arrays. They're objects, or at least they're being treated like objects. Even if they are Array instances, in other words, the "length" only tracks the largest numeric-indexed property.

JavaScript doesn't really have an "associative array" type.

You can count the number of properties in an object instance with something like this:

function numProps(obj) {
  var c = 0;
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) ++c;
  }
  return c;
}

Things get somewhat messy when you've got inheritance chains etc, and you have to work out what you want the semantics of that to be based on your own architecture.

Pointy
  • 405,095
  • 59
  • 585
  • 614
4

.length only works on arrays. It does not work on associative arrays / objects.

patientsData["XXXXX"] is not an array. It's a object. Here's a simple example of your problem:

var data = {firstName: 'a name'};
alert(data.length); //undefined
Eric
  • 95,302
  • 53
  • 242
  • 374
0

It appears that you are not using nested array, but are using objects nested within objects because you're accessing members by their names (rather than indexes).

Wyatt
  • 1,366
  • 9
  • 14