March 5, 2011

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



Giving me +1 tells me you liked this article! Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "2D Array in JavaScript using Constructor Function"
 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions