What wrong with this code if I want to print my chessboard?


#1


The output is only a black box ("#"). I am desiring output to be a chessboard.


----------------------JScript CODE-------------------------------------------

var chessBoard = function (length, black) {
    var result = "";
    for (var line = 1; line <= length; line++) {
        for (var pair = 1; pair <= length; pair++) {
            result += "  " + black;
        }
        result += "<br />";
        for (var pair2 = 1; pair2 <= length; pair2++) {
            result += black + "  ";
        }
        result += "<br />";        
    }

    console.log(result);
    return result;
}

document.getElementById("testid").innerHTML = chessBoard(4, "#");

---------------------------------------HTML CODE---------------------------------------------
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>

</head>

<body>

    <div id="testid">Hello, here will be the pattern!</div>

    <script src="Script1.js" type="text/javascript"></script>
</body>
</html>
------------------------------------------------------------------------------------------------


#2

this is the output i get:

  #  #  #  #
#  #  #  #  
  #  #  #  #
#  #  #  #  
  #  #  #  #
#  #  #  #  
  #  #  #  #
#  #  #  #

i have to admit, on the webpage itself it doesn't look quit that nice, maybe you shouldn't use spaces, try using underscores instead:

var chessBoard = function (length, black) {
    var result = "";
    for (var line = 1; line <= length; line++) {
        for (var pair = 1; pair <= length; pair++) {
            result += "_" + black;
        }
        result += "<br />";
        for (var pair2 = 1; pair2 <= length; pair2++) {
            result += black + "_";
        }
        result += "<br />";        
    }

    console.log(result);
    return result;
}

document.getElementById("testid").innerHTML = chessBoard(4, "#");

then it looks much more like a chessboard


#3

and here is the underlying cause for the problem with spaces:

js removes all the spaces except one


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.