Creating and looping through a Javascript array by length

By | November 2, 2010

One of the projects I’m working on now requires the use of a Javascript array to store data we will parse through. Creating a Javascript array is a pretty straight forward process. First you define the variable object as an array and then define values to it as necessary. Here is an example in code:


var testArray = new Array();

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

As you see, you define the variable using the “new Array()” object definition, then assign values starting a zero. To loop or iterate through an array to read the values, you just need to create a basic for loop that uses the lenght attribute of the array object to determine the size. Here is a code example for that:

for(i=0;i

If you add the above code underneath the last array definition and run it, you should see thee javascript alerts showing each of the three defined array values. Anyway I hope this helps in your creation and parsing through of javascript arrays!