I am writing a Sudoku validator as a practice problem. I import an 81 digit board in a single line delimited by a single space as a string. When I print the string at line 4, there are no commas separating the digits in my input. At line 14 I use the split method to split it into an array that should be 81 indexes long. When I test it by printing the array at line 20, the indexes between the digits have been populated by commas. I do not know where these magic commas have come from, it must be a result of the split method since my input does not contain any commas. Can anyone explain what is happening? Here is the JS script:
function import1() {
var board = prompt("Please enter a board");
if (board != null) {
document.getElementById("demo").innerHTML = "board entered: " + board + "\n";
}
else {
document.getElementById("demo").innerHTML = "Invalid entry\n";
}
parseMe(board);
}
function parseMe(board) {
var boardArray = String(board.split(" "));
var toPrint = "";
for (var j = 0; j < boardArray.length; j++) {
toPrint += boardArray[j];
}
document.getElementById("test").innerHTML = "test" + toPrint;
var board2D = [
["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", "0", "0", "0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0", "0", "0", "0"]
];
var counter = 0;
for (var i = 0; i < board2D.length; i++) {
for (var j = 0; j < board2D.length; j++) {
board2D[i][j] = boardArray[counter];
counter++;
}
}
if (counter != 81) {
document.getElementById("error").innerHTML = "Invalid entry, should be 81 total digits\n";
}
printBoard(board2D);
}
function printBoard(board) {
var toPrint = "";
for (var i = 0; i < board.length; i++) {
for (var j = 0; j < board.length; j++) {
toPrint += board[i][j] + " ";
}
toPrint += "\n";
}
document.getElementById("printBoard").innerHTML = toPrint;
}
I can provide the webpage I'm writing to if anyone wants to see it, but I don't think it matters.
Here is what the output looks like:
board entered: 5 3 4 6 7 8 9 1 2 6 7 2 1 9 5 3 4 8 1 9 8 3 4 2 5 6 7 8 5 9 7 6 1 4 2 3 4 2 6 8 5 3 7 9 1 7 1 3 9 2 4 8 5 6 9 6 1 5 3 7 2 8 4 2 8 7 4 1 9 6 3 5 3 4 5 2 8 6 1 7 9
test5,3,4,6,7,8,9,1,2,6,7,2,1,9,5,3,4,8,1,9,8,3,4,2,5,6,7,8,5,9,7,6,1,4,2,3,4,2,6,8,5,3,7,9,1,7,1,3,9,2,4,8,5,6,9,6,1,5,3,7,2,8,4,2,8,7,4,1,9,6,3,5,3,4,5,2,8,6,1,7,9
boardArrayis not an array; it's a string (since you wrap it inString()). That causes it to useArray.prototype.toString, which uses a comma by default.boardArrayto actually be an Array you don't want to wrap it inString()--let boardArray = board.split(' ');