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">
function
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]);

</script>

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 = [[],[],[]];






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: