javascript程序
Today, we will write a function that forms a chessboard. You can find the exercise in the Eloquent Javascript book (3rd edition, chapter 2; Program Structure).
今天,我们将编写一个构成棋盘的函数。 您可以在Eloquent Javascript书(第3版,第2章;程序结构)中找到练习。
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 chessboard.
编写一个程序,该程序创建一个代表8×8网格的字符串,并使用换行符分隔各行。 在网格的每个位置都有一个空格或一个“#”字符。 角色应构成一个棋盘。
Passing this string to console.log
should show something like this:
将此字符串传递给 console.log
应该显示如下内容:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
Let’s start writing our function that takes a number as a parameter and generates a grid of the given size.
让我们开始编写将数字作为参数并生成给定大小的网格的函数。
Here are the steps that we will follow to write this program:
这是我们编写该程序将遵循的步骤:
Declare a variable of an empty string that stores a space (
“ ”
) or a hash (“#”
) or a newline (“\n”
).声明一个空字符串的变量,该变量存储一个空格(
“ ”
)或一个哈希(“#”
)或一个换行符(“\n”
)。Set a loop inside of a loop to generate a two dimensional grid: An outer loop is for rows to set board height (
“i”
) and the inner loop is for columns to set board width (“j”
).在循环内部设置一个循环以生成二维网格:外部循环用于行以设置板高度(
“i”
),内部循环用于列以设置板宽(“j”
)。Start building the string line by line from left to right and top to bottom by checking the sum of the two counters (
(i + j)%2==0
).通过检查两个计数器的和(
(i + j)%2==0
),开始从左到右,从上到下逐行构建字符串。If the sum of the two counters is even; put a space (
“ ”
), if it is not even; then add a hash (“#”
) character to the string.如果两个计数器的总和为偶数; 如果不均匀,则放置一个空格(
“ ”
); 然后在字符串中添加一个井号(“#”
)。Whenever the inner loop finishes, add (
“\n”
) character to the string to generate a new line and then move to the next row.每当内部循环结束时,在字符串中添加(
“\n”
)字符以生成新行,然后移至下一行。- Return the result by printing the grid to the console. 通过将网格打印到控制台来返回结果。
The following code summarizes the steps we have listed above in JavaScript:
以下代码总结了我们在JavaScript中上面列出的步骤:
![Image for post](https://img-service.csdnimg.cn/img_convert/866127fc9527920e5303948c90a28684.png)
Every inner loop represents a line and handles the characters on that line by adding either a space (“ ”
) or hash (“#”
) to the string. Inside the outer loop; after each line is built, a newline character (“\n”
) is added to the string to move to the next line. This function not only works for an 8 X 8 grid, but it also works for any size by receiving a number as a parameter; num.
每个内部循环都代表一行,并通过在字符串上添加空格( “ ”
)或哈希( “#”
)来处理该行上的字符。 在外循环内部; 在构建每行之后,在字符串中添加一个换行符( “\n”
)以移至下一行。 此函数不仅适用于8 X 8网格 ,而且还可以通过接收数字作为参数来适用于任何大小。 num 。
Thanks for reading! If you find this helpful, check out my other posts on JavaScript algorithms:
谢谢阅读! 如果您觉得这有帮助,请查看我有关JavaScript算法的其他文章:
翻译自: https://medium.com/swlh/javascript-chessboard-program-6740c855e44f
javascript程序