Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  21] [ 4]  / answers: 1 / hits: 25247  / 13 Years ago, thu, august 25, 2011, 12:00:00

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?


More From » arrays

 Answers
121

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.


[#90412] Wednesday, August 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;