Doen
Doen

Reputation: 33

Initializing the 2D array elements in javascript

I want to initialize and then print the elements of a 2D array using javascript. I wrote this code but nothing displays as output. How to output this array?

var m = 6;
var n = 3;
var mat = new Array[m][n];

for (i = 0; i < mat.length; i++) {
  for (j = 0; j < mat[i].length; j++) {
    mat[i][j]) = i * j;
    document.writeln(mat[i][j]);
  }
  document.writeln("<br />");
}

Upvotes: 1

Views: 280

Answers (3)

Stewart
Stewart

Reputation: 3161

Javascript arrays are dynamic. They will grow to the size you require. You can call push() to add a new element to the array. It's also worth noting that you should avoid using the new keyword with objects and arrays. Use their literal notations [] for arrays and {} for objects. So a better solution here would be to push to the arrays as you need them.

var mat = [];
var m = 6;
var n = 3;
for (var i = 0; i < m; i++) {
  // Let's add an empty array to our main array
  mat.push([]);
  for (var j = 0; j < n; j++) {
    mat[i].push(i * j);
    document.writeln(i * j);
  }
  document.writeln('<br />');
}

Upvotes: 0

Z.Z.
Z.Z.

Reputation: 704

<html>
    <body>
    </body>
    <script>
        var m=6;
        var n=3;
        var mat =new Array(m);

        for( var i=0; i < m ; i++){

            mat[i] = new Array(n);

            for( var j=0;j< n ;j++){
                mat[i][j] = i*j;
                document.writeln(mat[i][j]);
            }

            document.writeln("<br />");
        }
    </script>
</html>
   

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

As BenG pointed out, you've got an extra ) but you also aren't initializing your array correctly. Javascript doesn't allow you to declare multi-dimensional arrays like other languages. Instead, you'd have to do something more like this:

var m = 6;
var n = 3;
var mat = new Array(m);
for (var i = 0; i < m; i++) {
  mat[i] = new Array(n);
}

Upvotes: 1

Related Questions