开发者

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 开发者_如何学JAVAthat 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/


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.


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


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


Or, rearrange your array like this:

var array = [];

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

alert(array.length); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜