Two Dimensional Arrays in JavaScript

JavaScript does not provide any direct notion of creating multi dimensional arrays as provided by languages like, C and Java. But there are ways to solve this problem and create a multi dimensional array.
Below we are trying to create a two dimensional array. The idea is simple and can be applied to create arrays with more than two dimensions:

function init2DArray(
    var twoDArray;
    var cols = 10, rows = 15;
    var indexI;
    twoDArray = new Array(cols);
    for (indexI = 0; indexI < cols; indexI += 1) {
        twoDArray[indexI] = new Array(rows);
        for( indexJ = 0; indexJ < rows; indexJ += 1) {
            twoDArray[indexI][indexJ] = 0;
        }
    }
}

Now since we have got the 2D array, we may want to initialize it with something (may be with a default value).
Simply add the add the following code in the for loop after the first line:

for( indexJ = 0; indexJ < rows; indexJ += 1) {
    twoDArray[indexI][indexJ] = 0;
}

I have tried to make the code above error free but if anly problem persists, please post it in the comments. Also please feel free to suggest any optimization in the code.

Advertisements

One thought on “Two Dimensional Arrays in JavaScript

  1. Pingback: Simple Word Search Generator JavaScript HTML | Randomly Picked

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s