-1

Here is my code:

board = [];

var rowsNum = 5;
var colsNum = 5;

function printBoard(board) {
    for (row in board) {
        document.write(" ").join(row);
    }
}

function clearAndRestartBoard() {
    board = [];
    for (i = 0; i < rowsNum; i++) {
        board.push("[ ]" * colsNum);
        }
}

printBoard(board);       

It does not throw an error, but it does not show up in my webpage. Do you know what I am doing wrong?

Just in case, here is the html without the css:

<!DOCTYPE html>
<html>
    <head>
        <link href="test.css" type="text/css"rel="stylesheet" />
        <title> Test! </title>
    </head>
    <body>
        <p id = "script"> <script src = "test.js"> </script> </p>
    </body>
</html>

I am very new to JS so thank you so much for any help!

Demandooda
  • 122
  • 1
  • 14

1 Answers1

6

There are several issues there, but the main one is that you never call clearAndRestartBoard, and so board is empty, and so you never output anything.

Here's a list of all of the issues that I see off-the-cuff:

  1. You never call clearAndRestartBoard.

  2. Your code is falling prey to The Horror of Implicit Globals: Declare your variables.

  3. You're using for-in to loop through an array. That's usually not a good idea, though there can be use cases for it; this answer outlines your various options for looping through an array.

  4. "[ ]" * colsNum is NaN because * will convert both of its operands to numbers and then do mathematical multiplication. The string "[ ]" converts to NaN because it cannot be interpreted as a number, and then anything multiplied by NaN is NaN. It isn't colsNum blank arrays. To do that, you'd have to have a second loop creating the row arrays, pushing "[ ]" into them, and pushing those row arrays onto board.

  5. You're using document.write. While that will work for simple experiments, it's not something you want to use in general.

  6. You're calling join on the result of document.write, which I'm fairly certain isn't an array.

  7. I would also suggest that you either use a global board, or always pass it as an argument, but not mix-and-match where one function uses the global and the other uses an argument.

  8. You never output a line break between rows.

Here's a minimal update addressing those:

var board;

var rowsNum = 5;
var colsNum = 5;

function printBoard(board) {
  board.forEach(function(row) {
    document.write(row.join(""));
    document.write("<br>");
  });
}

function clearAndRestartBoard() {
  var row;
  board = [];
  for (var r = 0; r < rowsNum; r++) {
    row = [];
    for (var c = 0; c < colsNum; c++) {
      row.push("[ ]"); // If you really wanted the string [ ]
    }
    board.push(row);
  }
}

clearAndRestartBoard();
printBoard(board);
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875