Monday, November 26, 2012

Javascript Array

Javascript Array

An array is a variable that can store many variables within it. Many programmers have seen arrays in other languages, and they aren't that different in JavaScript.

Creating a JavaScript Array

Creating an array is slightly different from creating a normal variable. Because JavaScript has variables and properties associated with arrays, you have to use a special function to create a new array. This example shows how you would create a simple array, store values to it, and access these values.
JavaScript Code:

<script type="text/javascript">
<!--
var myArray = new Array();

myArray[0] = "Football";
myArray[1] = "Baseball";
myArray[2] = "Cricket";

document.write(myArray[0] + myArray[1] + myArray[2]);
//-->
</script>

Output:
FootballBaseballCricket

JavaScript Array Sorting

Imagine that you wanted to sort an array alphabetically before you wrote the array to the browser. Well, this code has already been written and can be accessed by using the Array's sort method.
JavaScript Code:

<script type="text/javascript">
<!--
var myArray2= new Array();

myArray2[0] = "Football";
myArray2[1] = "Baseball";
myArray2[2] = "Cricket";

myArray2.sort();

document.write(myArray2[0] + myArray2[1] + myArray2[2]);
//-->
</script>

Display:
BaseballCricketFootball

No comments:

Post a Comment