javascript 在jquery中查找数组的长度得到错误的结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29942698/
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-10-28 11:21:50  来源:igfitidea点击:

Find length of an array in jquery getting wrong result

javascriptarrays

提问by Shijin TR

I have javascript code like below to get the size of an array,

我有如下的 javascript 代码来获取数组的大小,

var testvar = [  ];
testvar[1] = 2;
testvar[200] = 3;
alert(testvar.length);    //201

Fiddle demo

小提琴演示

But the code alerts 201insted of getting the size 2,Why?

但是代码提示201获取大小2,为什么?

I need to get the count of total elements in that array.

我需要获取该数组中总元素的数量。

回答by Enjoyted

if you want to really find the length of your array despite doing such things :

如果你想在做这些事情的情况下真正找到数组的长度:

alert(Object.keys(testvar).length);

https://jsfiddle.net/4Lqsf45a/

https://jsfiddle.net/4Lqsf45a/

note that Object.keys()is not avaiable in IE < 9. see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keysfor workarounds

请注意,Object.keys()在 IE < 9 中不可用。有关变通方法,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

回答by devqon

Because you are setting a value at index 200 with testvar[200] = 3. The lengthproperty will be the last index of the array + 1.

因为您在索引 200 处使用testvar[200] = 3. 该length属性将是数组的最后一个索引 + 1。

For getting the total count of elements, you can use the following for example:

要获取元素的总数,您可以使用以下示例:

function countElements(arr) {
    var numElements = 0;
    for ( var indx in arr ) {
        numElements ++;
    }
    return numElements;
}

回答by Robusto

JavaScript allows sparsearrays, which means you can have an array with two elements, but the length of the array is pegged to the indexfor the last element, and is achieved by adding 1 to the last index. So if your last index is 200, the length reported for the array will be 201.

JavaScript 允许使用稀疏数组,这意味着您可以拥有一个包含两个元素的数组,但数组的长度与最后一个元素的索引挂钩,并通过在最后一个索引上加 1 来实现。因此,如果您的最后一个索引是 200,则为数组报告的长度将为 201。

See this SO questionfor more detail.

有关更多详细信息,请参阅此 SO 问题

回答by Trader

This should get the correct number of elements:

这应该得到正确数量的元素:

testvar.filter(function(value) { return value !== undefined }).length;

回答by Mathijs Segers

Because you cannot assign values this way. What you just did is create an array which has 200 length (including 0).

因为您不能以这种方式分配值。您刚刚所做的是创建一个长度为 200(包括 0)的数组。

You should probably use an object for what you're doing instead.

您可能应该使用一个对象来代替您正在做的事情。

I believe what you try to do only works in PHP arrays

我相信您尝试做的仅适用于 PHP 数组

enter image description here

在此处输入图片说明

回答by Rouby

the length property says nothing about the number of defined values in the array.

length 属性没有说明数组中已定义值的数量。

To get the count of defined items you could use something like this

要获得定义项目的数量,您可以使用这样的东西

var count = array.filter(function(value) { return value !== undefined }).length

var count = array.filter(function(value) { return value !== undefined }).length

回答by Saty

try this

试试这个

var testvar = [  ];
testvar[1] = 2;
testvar[200] = 3;

var size = testvar.filter(function(value) { return value !== undefined }).length;

console.log(size);

output

输出

2

回答by Shashank Singh

You can do by this way, its working.

你可以这样做,它的工作。

<script>
 var testvar = new Object();
 testvar["1"] = 2;
 testvar["200"] = 3;

 Object.size = function(obj) {
  var size = 0, key;
  for (key in obj) {
     if (obj.hasOwnProperty(key)) size++;
  }
  return size;
 };

 // Get the size of an object
var size = Object.size(testvar);
 alert(size);
 </script>

回答by Michael Baarz

Yes, how the prior answer said. Javascript arrays are null based, and they have a length with starts at 0, every time.

是的,先前的答案是怎么说的。Javascript 数组是基于空值的,并且它们的长度每次都从 0 开始。

What do you want to archive? Getting only the length of a list you have?

你想存档什​​么?仅获取您拥有的列表的长度?

Why do you set the 3 to position 200? Is that needed for your code?

为什么将 3 设置为位置 200?你的代码需要吗?

What you can do is:

你可以做的是:

var testvar = {'1': 2, '200': 3};

function length(arr) {
  var c = 0;
  for(prop in arr) {
     if(typeof arr[prop]=='number')
       c++;
  }
  return c;
}
length(testvar);

This gives you the correct length!

这给你正确的长度!

回答by andlrc

Because you are adding an item at index 200, which will resolve in the array being padded up with a lot of undefined values, if you want to find all non undefined values you could use:

因为您要在索引 200 处添加一个项目,这将在用大量未定义值填充的数组中解析,如果您想查找所有未定义值,您可以使用:

var sum = testvar.reduce(function(sum) { return sum+1; }, 0); // 2


JavaScript doesn't support associative arrays, but you can use objects instead:

JavaScript 不支持关联数组,但您可以使用对象代替:

var a = {};
a[1] = 1;
a[200] = 1;

// To get the length is a little tricky
var length = Object.keys(a).length; // 2