1

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 />");
}
1
  • 1
    Note, it's not necessary to initialize the array with its dimensions. You can do var mat = []; and still get the results you'd like, as long as you change your loops accordingly Commented Feb 11, 2016 at 21:14

3 Answers 3

1

<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>
   

Sign up to request clarification or add additional context in comments.

1 Comment

@Doen You are welcome. Here is good practice of How to Create 2D Array in JavaScript
1

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);
}

Comments

0

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 />');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.