3

thank you in advance for taking the time to help me with this question.

I am trying to generate a simple board like so, using a for loop.

var board = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]];

However, my attempt below has not been successful.

function makeBoard(n){
  var board=[];
  for(var i=0; i<n; i++){
    for(var j=0; j<n; j++){
      board[i][j]=0;
    }
  }
  return board;
}

Technically, I could just use the board variable I have shown above, and continue, but I am more concerned with the principle. Is it not possible to create a multidimensional array using for loop? Is there a simple way to accomplish this using array.push()?

0

3 Answers 3

3

JavaScript doesn't have multidimensional arrays, so you have to use an array of arrays instead:

function makeBoard(n){
  var board=[];
  for(var i=0; i<n; i++){
    board[i] = [];
    for(var j=0; j<n; j++){
      board[i][j]=0;
    }
  }
  return board;
}

You were missing the board[i] = []; needed to create each array for the second dimension.

Note: You could also use Array.prototype.fill:

function makeBoard(n){
  var board=[];
  for(var i=0; i<n; i++){
    board[i] = Array(n).fill( 0 );
  }
  return board;
}
Sign up to request clarification or add additional context in comments.

2 Comments

fill works only on selected user agents.
@isvforall That doesn't work, since Array.fill doesn't do a deep copy. You end up with board[0] === board[1] === board[2] ... all references to the same array
1

You need for every new sub array an initialisation as array:

function makeBoard(n){
    var board=[];
    for(var i=0; i<n; i++){
        board[i] = []; // <-- this is missing!
        for(var j=0; j<n; j++){
            board[i][j]=0;
        }
    }
    return board;
}
document.write('<pre>' + JSON.stringify(makeBoard(5), 0, 4) + '</pre>');

Another version without for loop

function makeBoard(n){
    return Array.apply(null, {length: n}).map(function () {
        return Array.apply(null, {length: n}).map(function () {
            return 0;
        });
    });
}
document.write('<pre>' + JSON.stringify(makeBoard(5), 0, 4) + '</pre>');

Comments

0

You generate an array and then loop new arrays inside of that. Something like this:

var arr = new Array(10);
for (var i = 0; i < 10; i++) {
  arr[i] = new Array(6);
}

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.