JS Arrays

Arrays are simply an ordered stack of data items with the same data type. Using arrays, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.

Most programming languages use similar syntax to create arrays. JavaScript arrays are created by first assigning an array object to a variable name, then by assigning values to the array.

var array_name = new Array(number_of_elements) array_name[0] = "Array element" or var faq = new Array(3) faq[0] = "What are JavaScript arrays" faq[1] = "How to create arrays in JavaScript?" faq[2] = "What are two dimensional arrays?"

You can access an array element by referring to the name of the array and the element's index number.

Displaying an array elements: document.write(faq[1]) The above statement displays the second element of the array named faq (note: array index numbers begin at zero in JavaScript). In this case, the value would be How to create arrays in JavaScript?

You can modify the contents of an array by specifying a value for a given index number: faq[1] = "How to modify an array?" The value of the second element of the above array would now be "How to modify an array?"

Two Dimensional Arrays
Whereas, one dimensional arrays can be visualized as a stack of elements, two dimensional arrays can be visualized as a multicolumn table or grid.

Generally, creating two dimensional arrays is very similar to creating one dimensional arrays. Some languages allow you to create two dimensional arrays simply by adding an index item, however JavaScript doesn't support two dimensional arrays.

JavaScript, does however, allow you to simulate a two dimensional array. You can do this by creating an "array of an array".

To do this, you create an array, loop through the array, and for each element, you create another array. Then, you simply add an index for each column of your grid. In JavaSript this would look something like this:

var faq = new Array(3) for (i=0; i &lt;3; i++) faq[i]=new Array(3) faq[0][1] = "Arrays" faq[0][2] = "What is an array?" faq[0][3] = "An ordered stack of data" faq[1][1] = "Arrays" faq[1][2] = "How to create arrays?" faq[1][3] = "Assign variable name to array object, then assign values to the array." faq[2][1] = "Arrays" faq[2][2] = "What are two dimensional arrays?" faq[2][3] = "An ordered grid of data"