Javascript arrays
Array:
1. Definition
We declare an array of n elements as follows:
var ARRAY = new Array();
ARRAY[0] = value0;
...
ARRAY[n-1] = valueN;
The value could be number or string.
Example:
We declare an array as follows:
var rare_gases = new Array();
rare_gases[0] = "helium";
rare_gases[1] = "neon";
rare_gases[2] = "argon";
rare_gases[3] = "krypton";
rare_gases[4] = "xenon";
rare_gases[5] = "radon";
We use the for...in statement to loop through the
elements of an array.
Syntax:
for (variable in array)
{
some code to be executed ...
}
2. Example:
<body>
<script type="text/javascript">
var atom;
var rare_gases = new Array();
rare_gases[0] = "helium";
rare_gases[1] = "neon";
rare_gases[2] = "argon";
rare_gases[3] = "krypton";
rare_gases[4] = "xenon";
rare_gases[5] = "radon";
for (atom in rare_gases)
{
document.write("- " + rare_gases[atom] + "<br />");
}
</script>
</body>
Will output:
- helium
- neon
- argon
- krypton
- xenon
- radon
3. Sorting an array:
Here is an example:
<head>
<script type="text/javascript">
function initialize(the_array) {
for (var i=0; i<the_array.length; i++)
the_array[i] = Math.floor(Math.random()*100)
}
function display(the_array) {
document.write('(');
for (var i=0; i<the_array.length; i++) {
if (i != 0)
document.write(', ');
document.write(the_array[i]);
}
document.writeln(')<br>');
}
function sorting(the_array) {
var minpos;
var intermed;
for (var j=0; j<the_array.length-1; j++) {
minpos=j;
for (var i=j+1; i<the_array.length; i++) {
if (the_array[i] < the_array[minpos])
minpos = i;
}
intermed = the_array[j];
the_array[j] = the_array[minpos];
the_array[minpos] = intermed;
}
}
// -->
</script>
</head>
<body>
<script type="text/javascript">
//create an instance object: an empty arrat
var the_array = new Array(20);
//then apply the metods defined in the head section:
initialize(the_array);
document.writeln('<H4>This an array of random numbers</H4>');
display(the_array);
sorting(the_array);
document.writeln('<BR> <H4>The same array after swapping</H4>');
display(the_array);
</script>
</body>
The output is:
3. Creating an array:
An array can be created using two methods:
1. The JavaScript Array object:
var atom = new Array();
atom is an array.
We can also write:
var atom = new Array(N)
That is the array atom will have N elements.
We fill in the array as follows:
atom [0] = 'Helium';
atom [1] = 'Neon';
atom [2] = 'Argon';
or directly:
atom = new Array("Helium", "Neon","Argon");
2. Constructing an array manually using a makeArray() function.
function makeArray() {
for (i = 0; i var atom = new makeArray("Helium", "Neon","Argon");
Example:
deck = new makeArray(13);
for (i=0; i<13; i++) {
deck[i] = i;
}
|