arrayname.length ==> alternative??

M

Marco Snoek

Hi,

Array('s) like:
customer[1]="John Doe";
items[1][34]="abc";
items[1][422]="aadsfasdf";
customer[2]="Pietje Puk";
items[2][3545]="asdfasdfasdf";
items[2][133]="asdfasdf";
items[2][1155]="sdkk;lj,8i";
etc..

Now: items[2].length is _not_ returning 3 (or 2 whatever point of view :)..
Any alternative for:
for(anItem in items[2]) { count++; }

??
Thanx in advance,
Marco Snoek
 
M

Michael Winter

On Sun, 19 Sep 2004 08:45:54 +0200, wrote:

[snip]
customer[2]="Pietje Puk";
items[2][3545]="asdfasdfasdf";
items[2][133]="asdfasdf";
items[2][1155]="sdkk;lj,8i";
etc..

Now: items[2].length is _not_ returning 3 (or 2 whatever point of view
:)..

No, it won't. Arrays in ECMAScript are sparse arrays: all elements that
aren't explicitly defined between two indicies are given the value,
undefined. So, if you wrote:

var a = [];
a[100] = 'a value';

there would be one explicitly defined value at index 100, and 100
undefined elements before it giving a length of 101.
Any alternative for:
for(anItem in items[2]) { count++; }

The for..in statement seems to be the only way to move through the defined
elements.

[snip]

Mike
 
L

Lasse Reichstein Nielsen

Marco Snoek said:
items[2][3545]="asdfasdfasdf";
items[2][133]="asdfasdf";
items[2][1155]="sdkk;lj,8i";
etc..

Now: items[2].length is _not_ returning 3 (or 2 whatever point of view :)..

No, it gives 3546, one larger than the largest index of an element of
the array.
Any alternative for:
for(anItem in items[2]) { count++; }

No, short of keeping track of how many entries have been assigned
yourself.

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top