Arrays:
Arrays are special type of javascript objects.
It is used to store data's in contiguous manner. In other
words arrays help you to store similar data's under one name
in a defined order.
Syntax:
var varname = new Array(3);
In the above syntax we have declared a new array of size 3 under the name varname.
We can create new array only using the syntax new Array. It is case sensitive
and so "Array" should not be defined as "array".
The size of the array is set as 3. So, we can store 3 variables in the array varname.
It can be declared with any size according to our requirement.
Assigning Vales:
Arrays always start from 0th
index or position. If we have set the size as 3, the array will have 3 position 0,1 & 2.
We can assign values to the array as follows,
varname[0] = "testing array";
varname[1] = "position 2";
varname[2] = "position 3";
To assign a value in to an array, we have to call the variable name on which the array was created,
followed by the position [where we want to store the value] and then assign the value.
Retrieving Values:
To retrieve a value from an array is very simple.
Just calling the array with its position will retrieve the value at that position in the
array.
E.g: var val = varname[0];
Example Code:
<script language="javascript">
var varname = new Array(2);
varname[0] = "testing array";
varname[1] = "position 2";
document.write("Result of array is - "+varname[1]);
</script>
Result:
The above example shows how to create a new array of size two, add values in to array and retrieve them.
In next tutorial chapter, you will learn dense array, dynamic array..
|