Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array returns length as 0 always even there are elements in it [duplicate]

Tags:

javascript

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']];
like image 906
gullamahi Avatar asked Jun 10 '13 07:06

gullamahi


2 Answers

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

like image 140
Darin Dimitrov Avatar answered Oct 28 '22 12:10

Darin Dimitrov


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.

like image 38
Guffa Avatar answered Oct 28 '22 11:10

Guffa