View Full Version : The number of elements in a Javascript array??!?!
sandie
10-09-2002, 01:29 PM
I am trying to get the number of elements in an array in Javascript. Tried "my_array.length" but this returns the length liek it says but not the number of elements.
Anyhelp will be appreciated!!!
requestcode
10-09-2002, 01:57 PM
That does return the number of elements in the array. If your array is set up like this:
myarray[0]="some value"
myarray[1]="some value"
Then the statement var len=myarray.length will return 2. Since Javascript starts counting at zero instead of one then to use this in a for loop you would do this:
for(i=0;i<len;i++)
{do something}
The first time through it would reference the first entry and the second time through it would reference the second entry. Hope that helps.
sandie
10-09-2002, 02:04 PM
Thanks Requestcode for replying.
Let me give a scenario:-
var my_array = new Array();
my_array[0] = "Test"
my_array[6] = "Another test"
This maybe a silly example but it's for illustration purposes only.
Now my_array.length = 7 not 2
Is there some property like
my_array."elements" which yields 2 ??????
Garadon
10-09-2002, 02:21 PM
cause ur array got 7 elements 0-6
u could get the elements that is assigned a value by
var I,J=0;
var my_array = new Array();
my_array[0] = "Test";
my_array[6] = "Another test";
for(i=0;i<my_array.length ;i++)
{
if(my_array[I]!="")
{
J++;
}
}
that code would result in J being the number of elements in ur array with a value
requestcode
10-09-2002, 02:25 PM
Ok now I see what you mean. I was able to get the number of elements this way:
<SCRIPT LANGUAGE="JavaScript">
var count=0
var myarray = new Array()
myarray[0]="0"
myarray[6]="1"
for(i=0;i<myarray.length;i++)
{
if(myarray[i]!=null)
{count++}
}
alert(count)
</SCRIPT>
sandie
10-09-2002, 02:33 PM
Thank you very much gentleman.
Requestcode, please check my "silly" example,thoroughly.
You will notice the array has 7 elements(according to the length property) but there are only two elements indexed at 0 and 6
Garadon,I have tried it(your code), it worked.
Thanks a lot!!!!
adios
10-09-2002, 05:02 PM
Just FYI:
;) Sparse Arrays. (http://caucuscare.com/~roth/JAVASCRIPT/ch08_05.htm)
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.