Sanjeev’s Weblog

Mostly my techie notes, which could help any Java guy

Javascript : Array

There are three ways of defining an array:

1) regular array. Pass an optional integer argument to control array’s size.
var myfriends=new Array()
myfriends[0]=”John”
myfriends[1]=”Bob”
myfriends[2]=”Sue”

2) condensed array

var myfriends=new Array(“John”, “Bob”, “Sue”)

3) literal array

var myfriends=["John", "Bob", "Sue"]

Multi-Dimensional Arrays

Since an Array can store other Arrays you can get the benefit of multi-dimension arrays.

var x=[0,1,2,3,4,5];
var y=[x];
In the above example we created an array named x and assigned it as the first element in the array y. If we ask for the value of y[0] it will return the contents of x as a string because we didn’t specify an index.

var x=[0,1,2,3,4,5];
var y=[x];
document.writeln(y[0]); // Will output: 0,1,2,3,4,5

If we wanted the third index we’d access it this way

var x=[0,1,2,3,4,5];
var y=[x];
document.writeln(y[0][3]); // Will output: 2

There’s no defined limit to how many Arrays you can nest in this manner. For instance

document.writeln(bigArray[5][8][12][1])

would indicate bigArray’s 5th index held an array, who’s 8th index held an array, who’s 12th index held an array, who’s first index contains the data we want.

Array Length: Array can be iterated like below

for (var i=0; i<myArray.length; i++) {
}

March 11, 2008 Posted by urssanj00 | Javascript | | No Comments Yet

Some Common Javascript

Iterating Form elements – checkboxes
for(i=0;i<document.myform.elements.length;i++)
{
if(document.myform.elements[i].type == “checkbox”)
{
if(document.myform.elements[i].checked)
{
alert(document.myform.elements[i].name);
}
}
}//end of for loop

Selecting 3rd option in a dropdown
document.myform.mycomb0.selectedIndex = 2;

March 5, 2008 Posted by urssanj00 | Javascript | | No Comments Yet