最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Array Length Key Value - Stack Overflow

programmeradmin2浏览0评论

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.

/

EDIT: this is how I solved it thanks.

/

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/fmgc8/1/

EDIT: this is how I solved it thanks.

http://jsfiddle/fmgc8/4/

Share Improve this question edited Nov 2, 2010 at 14:32 aherrick asked Nov 2, 2010 at 11:22 aherrickaherrick 20.2k33 gold badges116 silver badges196 bronze badges 1
  • you can't use strings to index an array. javascript is converting your '12' to 12 – Geoff Commented Nov 2, 2010 at 11:29
Add a ment  | 

4 Answers 4

Reset to default 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.

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)

  1. 暂无评论