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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7193530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:18:05  来源:igfitidea点击:

Check Length of Multidimensional Arrays with Javascript

javascriptarraysmultidimensional-array

提问by BFTrick

Possible Duplicate:
Length of Javascript Associative Array

可能的重复:
Javascript 关联数组的长度

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?

想法?这可能与范围有关吗?数组是在函数之外声明和设置的。这可能与JSON有关吗?我从 eval() 语句创建了数组。为什么虚拟数组工作得很好?

采纳答案by Pointy

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.

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

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

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

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.

当您有继承链等时,事情会变得有些混乱,您必须根据您自己的架构确定您想要的语义。

回答by Eric

.lengthonly works on arrays. It does not work on associative arrays / objects.

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

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

patientsData["XXXXX"]不是数组。它是一个对象。这是您的问题的一个简单示例:

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

回答by Wyatt

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

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