5

I have a javascript array like below with several elements in it. When I try to read the length of the array I am always getting 0 as the length. Can any one tell me why this is like this.

My array is like this:

var pubs = new Array();
pubs['b41573bb'] =['Albx Swabian Alb Visitor Guide','','15.12.2007 09:32:52',['0afd894252c04e1d00257b6000667b25']];
pubs['6c21a507'] =['CaSH','','29.05.2013 14:03:35',['30500564d44749ff00257b7a004243e6']];
Antony
  • 14,900
  • 10
  • 46
  • 74
gullamahi
  • 107
  • 3
  • 11

3 Answers3

5

The reported length is correct, because the array is empty.

When you use a string (that doesn't represent a number) with the bracket syntax, you are not putting items in the array, you are putting properties in the array object.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
5

You seem to be confusing an array with object. What you have is not an array. An array can only have integer indexes. In your example you seem to be using some b41573bb and 6c21a507 which are not integers, so you don't have an array. You have a javascript object with those properties. An array would have looked like this:

var pubs = new Array();
pubs[0] = ['Albx Swabian Alb Visitor Guide','','15.12.2007 09:32:52',['0afd894252c04e1d00257b6000667b25']];
pubs[1] = ['CaSH','','29.05.2013 14:03:35',['30500564d44749ff00257b7a004243e6']];

Now when you call .length you will get the correct number of elements (2).

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    Thank you for your comments. I tried with this Object.keys(pubs).length and have got the correct length. – gullamahi Jun 10 '13 at 08:11
1

try this

<script type="text/javascript">
var pubs = new Array();
var b41573bb = new Array();
var c6c21a507 = new Array();
b41573bb.push['Albx Swabian Alb Visitor Guide', '', '15.12.2007 09:32:52', ['0afd894252c04e1d00257b6000667b25']];
c6c21a507.push['CaSH', '', '29.05.2013 14:03:35', ['30500564d44749ff00257b7a004243e6']];
pubs.push(b41573bb);
pubs.push(c6c21a507);
alert(pubs.length);

sangram parmar
  • 8,462
  • 2
  • 23
  • 47