使用 Javascript 检查多维数组的长度

发布于 2024-12-01 04:43:38 字数 567 浏览 0 评论 0原文

可能的重复:
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

乖乖 2024-12-08 04:43:38

这些不是数组。它们是物体,或者至少它们被当作物体对待。换句话说,即使它们是 Array 实例,“长度”也仅跟踪最大的数字索引属性。

JavaScript 并没有真正的“关联数组”类型。

您可以使用以下方法来计算对象实例中的属性数量:

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

当您拥有继承链等时,事情会变得有些混乱,并且您必须根据自己的体系结构找出您想要的语义。

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.

就像说晚安 2024-12-08 04:43:38

.length 仅适用于数组。它不适用于关联数组/对象。

患者数据[“XXXXX”]不是数组。它是一个物体。这是您的问题的一个简单示例:

var data = {firstName: 'a name'};
alert(data.length); //undefined

.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
橘寄 2024-12-08 04:43:38

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

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文