Javascript array returns length as 0 always, even it has elements

I have a javascript array as shown below with a few elements in it. When I try to read the length of an array, I always get 0 as the length. Can someone tell me why this is so?

My array looks 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']]; 
+4
source share
3 answers

It seems you are mixing an array with an object. You do not have an array. An array can have only integer indices. 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 these properties. An array would look 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).

+5
source

The specified length is correct because the array is empty.

When you use a string (which does not represent a number) with parenthesis syntax, you do not put elements in an array, you put properties in an array object.

+5
source

try it

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

+1
source

Source: https://habr.com/ru/post/1485380/


All Articles