如何解决Eloquent Javascript“Chess Board”?

前端之家收集整理的这篇文章主要介绍了如何解决Eloquent Javascript“Chess Board”?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
新编码器在这里试图学习JS.我已经使用了codecademy,现在正在使用Eloquent Javascript.我终于摸了一会儿后终于得到了一些东西……但它不起作用!我不太确定我是否从正确的角度接近这个但我确实知道我想使用循环来跟踪基于#的网格的打印进度.

Write a program that creates a string that represents an 8×8 grid,
using newline characters to separate lines. At each position of the
grid there is either a space or a “#” character. The characters should
form a chess board.
Passing this string to console.log should show something like this:

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

我的代码如下:

var chessBoard = "";
    var size = 8;

    for (var lineCounter = 1; lineCounter < size; lineCounter++) { 

        if (lineCounter%2 === 0) { /

/if lineCounter is an even number
        for (var charCounter = 1; charCounter < size; charCounter++) {
            var evenOdd = (charCounter%2 === 0);
            switch (evenOdd) {
                case true:
                    (chessBoard += "#");
                    break;
                case false:
                    (chessBoard += " ");
                    break;
                }
            }                   
        }
    else { //if lineCounter is an odd number
        for (var charCounter = 1; charCounter < size; charCounter++) {
            var evenOdd = (charCounter%2 === 0);
            switch (evenOdd) {
                case true:
                    (chessBoard += " ");
                    break;
                case false:
                    (chessBoard += "#");
                    break;
            }
            }                       
        }   
    chessBoard += "\n";
    }
    console.log(chessBoard);

该程序的当前输出是这样的:

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

通过一些迭代,我已经学到了很多东西,但是现在我已经看到了一个错误 – 我明显是一个7×7网格,而不是我想要的8×8网格.我怀疑它与我使用“<”有关在我的for循环中,但不确定是否有更好的方法解决这个问题,而不是仅仅添加一个额外的数字.

解决方法

实际上你需要做两个循环很简单,
每行一个,另一个用于选择想要console.log的元素(”或’#’).

通过解决方案检查评论

var size = 8; //this is the variable setting

var board = "";//this is the empty string we're going to add either ' ','#' or newline

for (var y = 0; y < size; y++) {   /*in the outer loop we add newline to seperate rows*/
  for (var x = 0; x < size; x++) {/*every inner loop rappresents a line,and alternatively it's adding either ' ' or '#' to the string that's being populated*/
    if ((x + y) % 2 == 0)
      board += " ";
    else
      board += "#";
  }
  board += "\n";
}

console.log(board);

猜你在找的JavaScript相关文章