Ethiopian Review

Science and Technology News Digest

HOME | CONTACT | FORUM | ALBUM


JavaScript Two Dimensional Array

September 12th, 2009 at 9:40 am |

Introduction
The JavaScript Reference does not specify any effective two-dimensional array. However, you can create one. I show you how to do that in this article.

You need to already know the meaning of one and two-dimensional arrays in order to understand this article.

Note: If you cannot see the code or if you think anything is missing in this article (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

The One Dimensional Array
The JavaScript reference specifies a one-dimensional array. Normally each element of the one-dimensional array is a literal (value). Now, here is the secret for a two-dimensional array: If you have a one-dimensional array and you make each element of the one-dimensional array, a new array, then you would have a two dimensional array.

Creating a Two-Dimensional Array
You start by creating a one-dimensional array as follows:

twoDArr = new Array();

Assume that you want a two-dimensional array of five rows; you would make five elements of the twoDArr array, new one-dimensional arrays, using the new operator. You do this:

twoDArr[0] = new Array();
twoDArr[1] = new Array();
twoDArr[2] = new Array();
twoDArr[3] = new Array();
twoDArr[4] = new Array();

With this you have a two-dimensional array. It is a rather long process compared to what you have in other languages, but you finally got your two dimensional array.

Note: With JavaScript you do not have to decide on the length of a one or two-dimensional array. So the above two-dimensional array code is OK. If you know the number of rows and if they are many, then assigning a new one-dimensional array for each row as done above would be tedious. You solve this problem by assigning the new one-dimensional arrays in a for-loop. In this light, the above two-dimensional array is created as follows:

twoDArr = new Array();

for (i=0; i {
twoDArr[i] = new Array();
}

Accessing Values
You access the value of a JavaScript 2D array as follows:

ArrayName[i][j]

where i is the row number and j is the column number. Row and column counting begins from zero.

So to access the value in row 2, column 4, for the above array, you would type,

twoDArr[1][3]

Example Code
Try the following code:

twoDArr = new Array();

twoDArr[0] = new Array();
twoDArr[1] = new Array();
twoDArr[2] = new Array();
twoDArr[3] = new Array();
twoDArr[4] = new Array();

twoDArr[2][3] = “two, three”;

alert(twoDArr[2][3]);

Application
Generally, you would use a two-dimensional array, when you have data in the form of a table (grid).

That is it; a rather long approach, but you still have what you want.

- AssociatedContent

- Loulith Galenzoga





Related Posts

No related posts.

Leave a Reply