1

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/

1
  • you can't use strings to index an array. javascript is converting your '12' to 12 Commented Nov 2, 2010 at 11:29

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

1

Or, rearrange your array like this:

var array = [];

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

alert(array.length); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.