Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

js syntax : array

Status
Not open for further replies.

tyris

Programmer
Nov 2, 2000
311
FR
hi all,

i do have an array :

var myarray = new Array();
myarray[0] = new Array('val1','val2');

if i want to add later other elements to the array myarray[0] like this
for example : myarray[0] = new Array('val1','val2','val3');
what must i do ?
Best regards X-),
Elise
 
myarray[myarray.length] = value;

since all javaScript arrays are 0 based, that will tack one element on to the end, preserving all existing data.

:)
Paul Prewett
 
well i've made this little test :

var anarray = new Array();
anarray[0] = ('val1','val2');
anarray[anarray.length] = "val3";
for (i=0;i<=anarray.length;i++){
alert(anarray);
}

when when i execute this it gives me 3 msgbox with:
&quot;val2&quot; &quot;val3&quot; and &quot;undefined&quot;

and if i put this :

var anarray = new Array();
anarray[0] = new Array(&quot;val1&quot;,&quot;val2&quot;);
anarray[anarray.length] = &quot;val3&quot;;
for (i=0;i<=anarray.length;i++){
alert(anarray);
}

it gives me &quot;val1,val2&quot; &quot;val3&quot; &quot;undefined&quot;
it should give me &quot;val1&quot; &quot;val2&quot; val3&quot;
when is the porblem ? what didn't i understand ? Best regards X-),
Elise
 
for (i = 0; i < anarray.length; i++){
alert(anarray);
}

the array is 0 based, so notice where I have asked for the loop to stay explicitly less than .length --

it works much the same way as how you add it -- if you ask for .length, then the highest element is that number -1

:)
Paul Prewett
 
Hi Elise,

Try this,

<script>
var myarray = new Array();
myarray[0] = new Array('val1','val2');

alert(myarray[0]) // you should get &quot;val1, val2&quot;
myarray[0][2] = &quot;val3&quot;
alert(myarray[0]) // now you will get &quot;val1, val2, val3&quot;
</script>

hope this helps, Chiu Chan
WebMaster & Software Engineer
emagine solutions, inc
cchan@emagine-solutions.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top