Tuesday, March 15, 2011

Array in Javascript

The Array object is used to store multiple values in a single variable.
An array can hold all your variable values under a single name. And you can access the values by referring to the
array name.
Each element in the array has its own ID so that it can be easily accessed.


Create an Array
An array can be defined in three ways.
The following code creates an Array object called myCars:
1:
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab";       // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW"); // condensed array
3:
var myCars=["Saab","Volvo","BMW"]; // literal array
Note: If you specify numbers or true/false values inside the array then the variable type will be Number or Boolean,
instead of String.


Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index
number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab



Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel


*/
<html>
<body>

<script type="text/javascript">
var i;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + "<br />");
}
</script>

</body>
</html>

// concat two array

var parents = ["Jani", "Tove"];
var children = ["Cecilie", "Lone"];
var family = parents.concat(children);
document.write(family);


*/



No comments :

Post a Comment