aherrick
aherrick

Reputation: 20169

JavaScript Array Length Key Value

Why is this extremely basic JavaScript array giving me a length of 13 when there are only 3 key/value pairs in it. It makes sense that it might think 13 as 0 based index and my last array has a key of 12, but I need to have any array that has a key/value pair that returns me the correct number of pairs. The keys need to be numbers.

http://jsfiddle.net/fmgc8/1/

EDIT: this is how I solved it thanks.

http://jsfiddle.net/fmgc8/4/

Upvotes: 1

Views: 5416

Answers (4)

ArK
ArK

Reputation: 21068

There is no diffrence between array['12'] and array[12] (array['12'] is not considered as associative array element). To find associative array length

Upvotes: 1

Bitsplitter
Bitsplitter

Reputation: 980

Or, rearrange your array like this:

var array = [];

array.push(['10','ten']);    
array.push(['11','eleven']);    
array.push(['12','twelfe']);        

alert(array.length); 

Upvotes: 1

Victor Nicollet
Victor Nicollet

Reputation: 24577

The length property of arrays returns the biggest non-negative numeric key of the object, plus one. That's just the way it's defined.

If you want to count the key-value pairs, you're going to have to count them yourself (either by keeping track of them as they are added and removed, or by iterating through them).

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115498

it's because the highest number you have is:

array['12'] = 'twelve';

This creates an array length of 13 (since it's 0 based). JavaScript will expand the array to allocate the number of spots it needs to satisfy your specified slots. array[0..9] is there, you just haven't placed anything in them.

Upvotes: 6

Related Questions