Here are some useful advantages of using arrays:
- Less amount of coding for the programmer.
- Program will take up less memory, thus executes faster.
- Makes it easier to process related groups of data.
Declare Your Array
<arrayname> = new Array(<# of elements>);|
myArray = new Array(50);
*Just make sure that you capitalize the "A" in array on the right hand side of the equals sign. If not, you will get an error.
Now just to sort of discuss why arrays are important and useful. What if you needed to get the average of say, 50 numbers? Without an array, you would write 50+ lines of code. On the other hand, with an array you can accomplish this by 7 or 8 lines of code. And that would be the same if you needed to find the average of 100000 numbers. Instead of writing 100000 lines of code, 7 or 8 will do the trick.
Example of using an array to average numbers:
a = new Array(50);|
var x, sum;
sum = 0;
for (x=0; x <= 49; x++)
a[x] = x;
sum = sum + a[x];
avg = sum / 50;
document.write("The average is "+avg+"<br>");
*In the code sample we used a for loop. We will discuss these a bit later.
Joining Array Elements
Ok, what if you had an array and you wanted to combine each element to form a single sentence? Well, with the join(); function, it is quite simple! The join function will convert your array elements to a string. And a comma (,) is inserted between each element as it is converted. However, you can specify a different seperator.
array1 = new Array(5);|
array1 = "how";
array1 = "are";
array1 = "you";
array1 = "this";
array1 = "morning?";
x = array1.join(' ');
this would output: How are you this morning?
Notice my join function. it has ' ' included. This makes it output a space between each element. also doing just, .join(" "); would work. But if nothing was inside the ( and ), it would output: How,are,you,this,morning? It defaults with the comma. If you want anything different, you must specify it. Just make sure you sorround it with ' and ' becuase just .join( ) would make an error.
Sorting Array Elements
If sort(); is used on numbers, the numbers are sorted alphabetically instead of numerically. So say an array with: 1,2,3,4,11,22 would sort as: 1, 11, 2, 22, 3, 4. So basically sort(); has to be used with strings.
Heres an example of an array and the sort(); property:
array1 = new Array(5);|
array1 = "apples";
array1 = "banannas";
array1 = "oranges";
array1 = "pears";
array1 = "mangos";
sort = array1.sort();
This would output: apples,banannas,mangos,oranges,pears
Just as the .join(); function, you can enter html between the ( and ). So, if you put, .sort('<br>'); this would output each item on a line by itself. And using .sort(" "); would put a space between each item instead of a comma.
Example Program 3