使用 Javascript 检查多维数组的长度
可能的重复:
Javascript关联数组的长度
我想检查多维数组的长度,但我得到“未定义”作为返回。我假设我的代码做错了,但我看不出有什么奇怪的地方。
alert(patientsData.length); //undefined
alert(patientsData["XXXXX"].length); //undefined
alert(patientsData["XXXXX"]['firstName']); //a name
fruits = ["Banana", "Orange", "Apple", "Mango"];
alert(fruits.length); //4
想法?这可能与范围有关吗?该数组是在函数外部声明和设置的。这可能与 JSON 有关吗?我从 eval() 语句创建了该数组。为什么虚拟数组工作得很好?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这些不是数组。它们是物体,或者至少它们被当作物体对待。换句话说,即使它们是 Array 实例,“长度”也仅跟踪最大的数字索引属性。
JavaScript 并没有真正的“关联数组”类型。
您可以使用以下方法来计算对象实例中的属性数量:
当您拥有继承链等时,事情会变得有些混乱,并且您必须根据自己的体系结构找出您想要的语义。
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:
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
仅适用于数组。它不适用于关联数组/对象。患者数据[“XXXXX”]
不是数组。它是一个物体。这是您的问题的一个简单示例:.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:看来您没有使用嵌套数组,而是使用嵌套在对象中的对象,因为您是通过成员的名称(而不是索引)访问成员。
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).