2D Array in JavaScript using Constructor Function

In a previous post MultiDimensional Array in JavaScript , I had shown how to create a 2D array by creating instances of the Array object. A user asked me if there was a more generic way to do the same. Let us see one more way of creating a 2D array, using a constructor function:

<script type="text/javascript">
MultiDimArray(param1, param2) {
for (var x = 0; x < param1; ++x) {
this[x] = new Array(param2)

var newArr = new MultiDimArray(3, 3);
// Populate it as you want
newArr[0][0] = 100;
newArr[2][2] = 300;
// Print the values
document.writeln("Printing: " + newArr[0][0]);


In the example shown above, we are using a constructor function (called using ‘new’ operator) which uses a loop that executes 3 times and assigns an array of param2 elements to this[x].

As in the previous example, remember that two dimensional arrays do not exists in JavaScript. So what we are seeing here is a 1D array whose elements are 1D arrays. Also as pointed out by my friend Elijah Manor in the previous example, Douglas Crockford suggests to use the [] syntax to create Arrays: Eg: var arr = [[],[],[]];

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: