admin管理员组

文章数量:1208155

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

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

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

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

Fiddle demo

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

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

Share Improve this question edited Apr 30, 2015 at 13:00 Qantas 94 Heavy 16k31 gold badges72 silver badges88 bronze badges asked Apr 29, 2015 at 11:43 Shijin TRShijin TR 7,76811 gold badges62 silver badges125 bronze badges 4
  • the length property says nothing about the number of defined values in the array. – Jonathan Commented Apr 29, 2015 at 11:48
  • You can follow this link below stackoverflow.com/questions/5317298/… – Gaurav Agarwal Commented Apr 29, 2015 at 11:49
  • possible duplicate of Javascript count of array elements – Jonathan Commented Apr 29, 2015 at 11:50
  • the array.length value calculates the length just by adding 1 to the last index. That is the reason you get 201 instead of 2 – Harigovind R Commented Apr 29, 2015 at 11:52
Add a comment  | 

10 Answers 10

Reset to default 10

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

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

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/keys for workarounds

Because you are setting a value at index 200 with testvar[200] = 3. The length property will be the last index of the array + 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;
}

JavaScript allows sparse arrays, which means you can have an array with two elements, but the length of the array is pegged to the index for 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.

See this SO question for more detail.

This should get the correct number of elements:

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

Because you cannot assign values this way. What you just did is create an array which has 200 length (including 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

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

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

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

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

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>

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:

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

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

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

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

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

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?

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!

本文标签: javascriptFind length of an array in jquery getting wrong resultStack Overflow