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 = [[],[],[]];
Tweet
No comments:
Post a Comment