You should already know what an array is.
This sets up a JavaScript array:
var choices=new Array('chicken','beef','pork','vegetarian');
You can leave the values out and add them later.
var choices=new Array();
choices.push('chicken');
choices.push('beef');
PUSH adds a new element at the end of the array. SHIFT does the opposite and removes the first element in the array. POP gets the last element out and SPLICE removes:
choices.splice(2,1);
or replaces:
choices.splice(2,1,'pork');
a specified element. More traditionally you can do all this by assigning values:
var choices=new Array();
choices[0]='chicken';
choices[1]='beef';
To access the data in the array you identify which entry you want with a number in square brackets:
alert(choices[1]);
That would show beef in the dialog. Array numbering starts at zero so 1 is the second entry.
If you want to create an array with a set size but not put anything in it yet:
choices = new Array(4);
Finding things in arrays
The built in method indexOf() finds the array element which contains what you want:
fred=new Array('this', 'that', 'the other');
var location=fred.indexOf('that');
alert('At element '+location+' there is found the word '+fred["location"]);
Looping through arrays
By replacing the number in the square brackets with a variable (an incremented counter) or a test/condition you can more easily get at each entry in turn using loops. You can use FOR to go through all elements in the array or WHILE loops to go through until one matches the condition. These will be covered soon.
An array is an object and so has built in methods. The array object in JavaScript has a method which will do the same thing for every element in the array:
fred.forEach(somefunction());
This will send each element of the array to your function. It actually sends three items of data (the element vaue, it's index and the whole array contents) to the function. Try using ALERT in the function to display the contents of a simple array to see what happens:
function somefunction(value, index, wholearray){
alert('The value at location '+index+' within the whole array '+wholearray+' is '+value);
}
fred=new Array(5,2,8,7);
fred.forEach(somefunction);
Sorting array contents
Another method of the array object allows the sorting of it's contents:
somearray.sort();
This will sort alphabetically even if the values are numbers (so 11 comes before 2).
Multi-dimensional arrays
To create the main (top or parent) array do it as before:
playersarray = new Array(2);
Then create the array contained inside each element in the main array:
playersarray[0]= new Array(1);
playersarray[1]= new Array(2);
If you need to put lots of sub-arrays in a loop will help.
To put data into the sub-arrays:
playersarray[0][0]='Fred';
playersarray[0][1]='1/1/11';
playersarray[0][2]='20965';
playersarray[0][0]='Freda';
playersarray[0][1]='10/10/11';
playersarray[0][2]='25467';
To get the data out:
var player=playersarray[0][0];
var date=playersarray[0][1];




