Check Length of Multidimensional Arrays with Javascript

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?


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.


.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

看起来你并没有使用嵌套数组,而是使用嵌套在对象中的对象,因为你通过它们的名字(而不是索引)访问成员。

链接地址: http://www.djcxy.com/p/27258.html

上一篇: Object.length在javascript中未定义

下一篇: 用Javascript检查多维数组的长度