Multi-dimensional Arrays
Multi-dimensional array can be thought of as an array within an array. This type of an array will allow you to associate different objects to together. Let's say you want to list your favorite player for some sports, along with the team they play for. This is where a multi-dimensional array can come in handy. You can build the array, and then using a loop, display the information in the array.
<script language="JavaScript" type="text/JavaScript"> var sportStars = new Array ( ["Tim Duncan", "Basketball", "San Antonio Spurs"], ["David Becham", "Soccer", "Los Angeles Galaxy"], ["Peyton Manning", "Football", "Indianapolis Colts"], ["Josh Beckett", "Baseball", "Boston Red Sox"] ) </script>
This code creates the multi-dimensional array for us. As you can see we created an array called sportStars, then inside this array, we created four more arrays, which contain three values. Just like when you create an array there are different ways to make the multi-dimenstional arrays. Additionally, if we ever wanted to add an new sportsStar to our array, we could use the following.
sportStars[4] = ["Corey Perry", "Hockey", "Anaheim Ducks"];
To display any of the keys in the array we can use sportStarts[3][2]. This would display Indianaplois Colts, since it is the second key in the third key of sportStars. By using a loop, we can display this information in a table.
<script>
<table>
<tr>
<th width="150">Star
<th width="150">Sport
<th width="150">Team
</tr>
for (a=0;a<=3;a++){
document.write("<tr><td align='center'>" + sportStars[a][0] + "</td><td align='center'>" + sportStars[a][1] + "</td><td align='center'>" + sportStars[a][2] + "</td></tr>");
}
</table>
</script>
The output of this loop would look like the table below.
| Star | Sport | Team |
|---|
iEntry 10th Anniversary
CSS Snippets
JavaScript Snippets