简体   繁体   English

javascript用字符串创建网格

[英]javascript creating grid with string

I'm new to all of this and working through Eloquent JS. 我是这一切的新手,并通过Eloquent JS进行工作。 My goal here is a string that creates a chess board/grid of a given size, with spaces that consist of alternating hashes and blanks. 我的目标是创建一个字符串,该字符串创建给定大小的棋盘/棋盘,空格由交替的哈希和空白组成。 I don't quite understand 我不太明白

1.) the correct solution to my problem 1.)解决我的问题的正确方法

2.) what's happening when I make certain changes to the code 2.)当我对代码进行某些更改时会发生什么

This seems like it should be the correct answer but the first line in the console isn't aligned properly because of the comma: 这似乎应该是正确的答案,但是控制台中的第一行由于逗号而未正确对齐:

function chessBoard (size) {
result = "";
for (var i = 1; i <= size; i++) {
  for (var j = 1; j <= size; j++) {
    if ((i + j) % 2 == 0 ) {
      result = result + "#";        
  } else {
    result = result + " ";
    }

 }

result = result + "\n"
}
console.log(result);
}  

chessBoard(8);

"# # # # 
 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
"

If I change all 3 result statements inside the loops so the hash, space, and newline get placed on the other side of the + operator (result = "#" + result), the function produces: 如果更改循环内的所有3条结果语句,以便将哈希,空格和换行符放在+运算符的另一侧(结果=“#” +结果),则该函数将产生:

"
# # # # 
 # # # #
# # # # 
 # # # #
# # # # 
 # # # #
# # # # 
 # # # #"

That looks correct, but is it? 看起来正确,但是吗? Why does the first line start with a hash? 为什么第一行以哈希开头? If the inner loop is checking to see if (i + j) is even--last character is (1+8) right?--and then using 如果内部循环正在检查(i + j)是否为偶数-最后一个字符是(1 + 8)对吗?-然后使用

result = " " + result;

to add the last character to the string, why isn't that character at the beginning of the string? 将最后一个字符添加到字符串中,为什么不是在字符串开头的那个字符?

Lastly, if I use the result = result += order for the statements in the inner loops, but result = "\\n" + result in the outer loop, I get this: 最后,如果我对内部循环中的语句使用result = result + = order,但是在外部循环中使用result =“ \\ n” + result,我会得到:

"







# # # #  # # # ## # # #  # # # ## # # #  # # # ## # # #  # # # #"

What is happening here? 这是怎么回事 Thanks so much for the help. 非常感谢帮忙。

I'm going to try to explain how the code in the solution works. 我将尝试解释解决方案中的代码如何工作。

var size = 8;

var board = "";

for (var y = 0; y < size; y++) {
  for (var x = 0; x < size; x++) {
    if ((x + y) % 2 == 0)
      board += "#";
    else
      board += " ";
  }
  board += "\n";
}

console.log(board);

So you have a loop in a loop here. 因此,这里有一个循环。 The first/outer loop controls the line break and the inner one controls whether a # or a ' '(space) gets printed (aka added to the board variable). 第一个/外部循环控制换行,而内部循环控制是否打印#或''(空格)(又添加到board变量)。

Basically, what helps me is to imagine the inner loop going wild and adding spaces and # while the outer loop only really 'does' something (line break) every 8 times (or whatever the size variable). 基本上,对我有帮助的是想象一下内部循环会疯狂运行并添加空格和#,而外部循环只会每8次(或任何大小变量)真正“执行”某些操作(换行)。

So the inner loop runs and adds characters. 因此,内部循环会运行并添加字符。 Meanwhile, the outer loop just increases the y size. 同时,外部循环只会增加y的大小。 Every so often, it adds a new line to the board. 每隔一段时间,它就会向董事会添加新的一行。

I'm working on visualizing for loops so that I can understand them better. 我正在可视化循环,以便可以更好地理解它们。

Why does the first line start with a hash? 为什么第一行以哈希开头?

In the inner loop: 在内部循环中:

(i + j) % 2 == 0 ) 
   result = result + "#";      

on the first run, i is 1 and j is 1 , so 1+1 = 2 and it happens that 2%2==0 so the condition is true and therefore you are going to get a # at the beginning. 在第一次运行中, i1j1 ,所以1+1 = 2且碰巧2%2==0所以条件为真,因此您将在开始时获得#。

1) 1)

function chessboard(size){
    var i=0, _size=size*size, output='';
    for(;i<_size; i++){ 
        // add a new line if we need two
        if (i % size === 0)
               output= output +'\n' ;

        // determine whether we need a hash or a space
        output = output + (i%2 ? '#': ' ');     
    }
    // append a new line at the end for proper formatting.
    return output + '\n'
}

2) As you said the first line isn't aligned correctly because of the quote, so you need to add a new line character to the beginning. 2)正如您说的那样,由于引号导致第一行未正确对齐,因此您需要在开头添加新的行字符。

in the second set what you're doing is prepending to the string essentially building it backwards. 在第二组中,您正在做的事情是在字符串之前添加,本质上是向后构建它。 after each execution instead of adding the # or ' ' at the end of the string you're putting it at the beginning. 每次执行后,您无需在字符串末尾添加#或'',而是将其放在开头。 At the end you prepend the newline character to the beginning of the string which makes it start on a new line. 最后,您将换行符添加到字符串的开头,从而使它从新行开始。

I did some corrections using the Nimnam's solution to achieve the exactly second example pattern (I added some extra comments in the code too): 我使用Nimnam的解决方案进行了一些更正,以实现确切的第二个示例模式(我也在代码中添加了一些额外的注释):

function chessboard(size){
    // You have to multiply the (grid*1) * grid because the '\n' character. 
    // i.e If you have a 8 grid would need 72 grids (64 + 8 = 72) because each 
    // line would need a /n character, totaling 9 grids for each line.

    var i=0, _size=(size+1)*size, output='';
    for(;i<_size; i++){ 
        // add a new line if we need two
        // now we have to add +1 to the size because the 9º character;
        if (i % (size + 1) === 0)
           output= output +'\n' ;

        // determine whether we need a hash or a space
        // I inverted the character order to achieve the correct pattern
        output = output + (i%2 ? ' ': '#');     
    }
    // append a new line at the end for proper formatting.
    return output + '\n'
}

I hope it helps :) 希望对您有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM